Actually read AppSettings in ConfigureServices phase in ASP.NET Core

前端 未结 4 1301
刺人心
刺人心 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:06

    That is the way you can get the typed settings from appSettings.json right in ConfigureServices method:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
    
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure(Configuration.GetSection(nameof(MySettings)));
            services.AddSingleton(Configuration);
    
            // ...
    
            var settings = Configuration.GetSection(nameof(MySettings)).Get();
            int maxNumberOfSomething = settings.MaxNumberOfSomething;
    
            // ...
        }
    
        // ...
    }
    

提交回复
热议问题