简体   繁体   中英

How can I access IOptions (or any settings) from other tiers of my .NET Core app?

I have successfully tried and used IOptions from within a .NET Core Web API Controller.

For example, this works for me:

public MyController(IOptions<MySettings> options)
{
    // I can access these _options from any method in this Controller.
    _options = options.Value;
}

However, I need to access my IOptions from other tiers in my app.

For instance, perhaps I have this...

Controller --calls--> Business Layer --calls--> Data Access Layer

I really don't want to pass an IOptions parameter down the call chain. I've put MySettings in its own assembly to give all layers access to it.

  • Am I approaching this wrong?
  • What is the correct way to do this?
  • Is there a way to have IOptions automatically injected into the constructor like the Controller? (If so, how do I instantiate each class where I need this?)

Edit:

  • I'm not really concerned about dependencies, per-se, but the flow of info through a million "linked" tiers.

Controller(connection string from config) --calls--> Business Layer(connection string) --calls--> Data Access Layer(connection string)

I just used Connection String as an example.

Thanks.

You don't have to pass it down the chain. When you register your IOptions in Startup.cs its accessible to all your layers. DI container doesn't care where your IOptions are used for as long as that layer has dependency on IOptions and DI container knows which type to use to instantiate it.

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