Access to Configuration object from Startup class

前端 未结 1 1354
孤城傲影
孤城傲影 2020-12-20 20:23

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

相关标签:
1条回答
  • 2020-12-20 20:47

    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.

    0 讨论(0)
提交回复
热议问题