简体   繁体   中英

Net Core IOptions<AppSettings> use

I've followed the IOptions pattern in an MVC project and can inject my appsettings into my Controller:

public HomeController(IOptions<AppSettings> appSettings) {
    _appSettings = appSettings.Value;
}

I have a bunch of other classes that are instantiated from HomeController - can I directly inject into these as well or do I have to pass in _appSettings on each class instantiation?

Ideally all my classes would inject in the constructor, like the Controller.

Dependency injection is an all or nothing affair. If you're going to use DI, then you always use DI and virtually never manually new up anything (except basic classes like entities with no dependencies). In other words, if your controller is instantiating things that take dependencies, those things should be registered in the service collection and injected into the controller instead. For example, assuming you're doing something like:

public HomeController(IOptions<AppSettings> appSettings)
{
    _appSettings = appSettings.Value;
}

public IActionResult Foo()
{
    var service = new FooService(_appSettings);

    // do something
}

Then, you should add in your ConfigureServices :

services.AddScoped<FooService>();

And in your controller, you should instead be doing:

public HomeController(FooService fooService)
{
    _fooService = fooService
}

The service collection will take care of injecting your options into the service, since the service itself has a dependency on that.

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