Accessing the .NET Core configuration class from another assembly

In ancient days

In the web.config file, parameters can be placed in the appSettings section as follows:

<appSettings>
  <add key="mysetting" value="123"/>
</appSettings>

Despite the fact that my web.config file was in my web project, any assemblies / libraries used in this project could access the settings using:

ConfigurationManager.AppSettings["mysetting"]

Today (and the problem)

I am starting to use the .NET kernel, and as before, I have assemblies / libraries that are not web projects in their own right, and they need to access various configuration settings.

The Microsoft configuration documentation ( https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration ), along with all the other examples that I can find, have the configuration class consumed by the controller and provide no indication of how to make it work with the class in another assembly / library that is not a controller.

For ONE example, if I have a user attribute that I can decorate with a class, and this user attribute is defined in another library (not in a web project), and it needs to access the configuration settings, how to do it today? I also cannot pass anything to the constructor in such an instance.

+3
source share
2

, ASPNET Core, web.config.

.

IOptions<FooSettingsClass> , , , .

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

- . , , ( ) :

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

, , , , . :

public class SomeServiceInAnotherAssembly {
  public SomeServiceInAnotherAssembly(IOptions<FooSettingsClass> settings) {
    //..
  }
}

, , , FooSettingsClass ASPNET Core ( ), - , . - , .

, ( SomeServiceInAnotherAssembly) , .. services.AddScoped<SomeServiceInAnotherAssembly>();

, .

+1

8-2017 Microsoft System.Configuration .NET CORE v4.4. v4.5 v4.6 .

, .Net Framework CORE, . app.config, . , , appsettings.json, Microsoft . , FW. :

- [, ASP.NET CORE WEB API] app.config web.config appSettings configurationSection. web.config IIS. IIS web.config

netstandard20 DLL Asp.net Core Web Api, .

0

All Articles