Actually read AppSettings in ConfigureServices phase in ASP.NET Core

前端 未结 4 1273
刺人心
刺人心 2021-01-07 16:19

I need to setup a few dependencies (services) in the ConfigureServices method in an ASP.NET Core 1.0 web application.

The issue is that based on the new

4条回答
  •  不知归路
    2021-01-07 17:11

    Starting from ASP.NET Core 2.0 we do configuration setup in Program class when building WebHost instance. Example of such setup:

    return new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .ConfigureAppConfiguration((builderContext, config) =>
        {
            IHostingEnvironment env = builderContext.HostingEnvironment;
    
            config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
        })
    

    Among others, this allows using configuration directly in Startup class, getting an instance of IConfiguration via constructor injection (thank you, built-in DI container):

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
    
        ...
    }
    

提交回复
热议问题