Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

c# - Access to Configuration object from Startup class

I would like to access to the Active Directory from my company in many controllers from my ASP.NET vNext project, and I inserted the domain name into my config.json file, so I can access it from the Configuration class. I find it heavy to always instantiate a new Configuration object at every time I want to access to my config.json, is there any way through the IConfiguration API to access to the Configuration class initialized into the Startup class ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

An example of how you can do this:

Let's assume you have a config.json like below:

{
    "SomeSetting1": "some value here",
    "SomeSetting2": "some value here",
    "SomeSetting3": "some value here",
    "ActiveDirectory": {
        "DomainName": "DOMAIN-NAME-HERE"
    }
}

Create a POCO type having your option information:

public class ActiveDirectoryOptions
{
    public string DomainName { get; set; }
}

In Startup.cs, when configuring services:

services.Configure<ActiveDirectoryOptions>(optionsSetup =>
{
    //get from config.json file
    optionsSetup.DomainName = configuration.Get("ActiveDirectory:DomainName");
});

In all controllers which want to get this config setting, do something like...Here the options is injected by the DI system:

public class HomeController : Controller
{
    private readonly IOptions<ActiveDirectoryOptions> _activeDirectoryOptions;

    public HomeController(IOptions<ActiveDirectoryOptions> activeDirectoryOptions)
    {
        _activeDirectoryOptions = activeDirectoryOptions;
    }

    public IActionResult Index()
    {
        string domainName = _activeDirectoryOptions.Options.DomainName;

        ........
    }
}

Responding to the comment:
There are couple of options that I can think of:

  1. From within the action, you can do

    var options = HttpContext.RequestServices.GetRequiredService<IOptions<ActiveDirectoryOptions>>().Options;

  2. You can have a parameter to the action which is decorated with FromServicesAttribute. This attribute will cause the parameter value to be retrieved from the DI. Example:

    public IActionResult Index([FromServices] IOptions<ActiveDirectoryOptions> options)

I prefer #2 over #1 as in case of unit testing it gives you information on all dependent pieces.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...