简体   繁体   中英

Passing and maintaining configuration in a Class Library

I'm building a Repository in a class library that is separate from my Web API in order to maintain separation of concerns.

I want to store database configuration in my appsettings.json so that I can override these settings in Azure Web Apps. This provides me a path to have separate settings for local, pre-production, and production environments.

I'm assuming the best way to provide configuration settings to the repository is to read them from the Startup.cs and then pass them along to the class library.

What is the best way to store these settings to ensure they persist throughout the lifecycle of the application and ensure they don't get garbage collected?

you need to create a configuration class:

 public class MyLibraryConfiguration {

     public string PropertyOne {get;set;}
 }

and use it in your classes as a construction-time dependency:

 public class MyService {

      private readonly IOptions<MyLibraryConfiguration> config;
      public MyService(IOptions<MyLibraryConfiguration> config) {
          this.config = config;
      }
 }

than you have to register your dependencies and your config in the Startup.cs of the web project:

  services.Configure<MyLibraryConfiguration>(options => this.Configuration.GetSection("SectionName").Bind(options));
  services.AddScoped<MyService>();   

then you can use MyService injecting it at construction-time

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM