ASP.NET 5 (vNext) - Configuration

前端 未结 3 1987
耶瑟儿~
耶瑟儿~ 2021-02-08 18:58

I am trying to learn ASP.NET 5. I am using it on Mac OS X. At this time, I have a config.json file that looks like the following:

config.json

         


        
3条回答
  •  梦如初夏
    2021-02-08 19:03

    In your Startup class, first specify your configuration sources:

    private readonly IConfiguration configuration;
    
    public Startup(IHostingEnvironment env)
    {
        configuration = new Configuration()
            .AddJsonFile("config.json")
            .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
    }
    

    The env.EnvironmentName is something like "development" or "production". Suppose it is "development". The framework will try to pull configuration values from config.development.json first. If the requested values aren't there, or the config.development.json file doesn't exist, then the framework will try to pull the values from config.json.

    Configure your config.json sections as services like this:

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure(configuration.GetSubKey("AppSettings"));
        services.Configure(configuration.GetSubKey("DbSettings"));
        services.Configure(configuration.GetSubKey("EmailSettings"));
    }
    

    Calling Configure(IConfiguration) on the IServiceCollection registers the type IOptions in the dependency injection container. Note that you don't need your AppConfiguration class.

    Then specify dependencies to be injected like this:

    public class EmailController : Controller
    {
        private readonly IOptions emailSettings;
    
        public EmailController (IOptions emailSettings)
        {
            this.emailSettings = emailSettings;
        }
    
        public IActionResult Index()
        {
            string apiKey = emailSettings.Options.EmailApiKey;
            ...
        }
    }
    

提交回复
热议问题