ASP.NET 5 (vNext) - Getting a Configuration Setting

前端 未结 4 1721
别那么骄傲
别那么骄傲 2020-12-05 12:52

I\'m writing a basic app to learn ASP.NET 5. One area I find very confusing is configuration. Prior to ASP.NET 5, I could do the following:

var sett         


        
4条回答
  •  一整个雨季
    2020-12-05 13:33

    ASP.NET 5 makes heavy use of Dependency Injection, so if you are also using Dependency Injection then this is very simple. If you examine the sample MVC6 project, you can see how this works:

    First, there's a class AppSettings defined in Properties, which is a strongly-typed version of the options your class supports. In the sample project, this just contains SiteTitle.

    public class AppSettings
    {
        public string SiteTitle { get; set; }
    }
    

    Then, this class is initialised through dependency injection in ConfigureServices. Configuration here is the one you created in the constructor of the Startup class.

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure(Configuration.GetSubKey("AppSettings"));
        // ...
    }
    

    Then, assuming your class is instantiated by the dependency injection container, you can simply ask for an IOptions and you'll get one. For example, in a controller you could have the following:

    public class HomeController
    {
        private string _title;
        public HomeController(IOptions settings) 
        {
            _title = settings.Options.SiteTitle;
        }
    }
    

提交回复
热议问题