Access .NET Core Configuration Class From Another Assembly

后端 未结 2 1272
感情败类
感情败类 2021-01-20 10:59

In The Olden Days

In a web.config file, settings could be placed in an appSettings section like so:


  

        
2条回答
  •  迷失自我
    2021-01-20 11:29

    I'm going to assume you're talking about a ASPNET Core project as you specifically mention web.config.

    Here's what you need to do.

    IOptions is usually configured at application start which means that it's available at runtime with code that looks something like this.

    // Adds services required for using options.
    services.AddOptions();
    services.Configure(Configuration.GetSection("FooAppSettings"));
    

    The easiest way is to have the framework inject it through the constructor. Typically you'll see it (as you mentioned) being injected in the controller like this:

    class FooController : Controller {
      public FooController(IOptions settings) { .
        //.. 
      }
    }
    

    If you need to access this configuration is say, a service, then you simply have a constructor, in a different assembly, which accepts those options. So:

    public class SomeServiceInAnotherAssembly {
      public SomeServiceInAnotherAssembly(IOptions settings) {
        //..
      }
    }
    

    This obviously means that your FooSettingsClass class needs to be outside of your ASPNET Core project (to avoid circular dependencies), but this is one way of propagating your configuration without writing any code, which is what I've seen other developers do. To me, writing code is a hoop jumping solution bound to have bugs.

    Don't forget that your class (in this exampe SomeServiceInAnotherAssembly) needs to be registered at startup, i.e. services.AddScoped();

    The nice thing about this approach is that it makes your classes testable.

提交回复
热议问题