Actually read AppSettings in ConfigureServices phase in ASP.NET Core

核能气质少年 提交于 2019-12-03 23:27:15

问题


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 JSON configuration I need to setup a service or another.

I can't seem to actually read the settings in the ConfigureServices phase of the app lifetime:

public void ConfigureServices(IServiceCollection services)
{
    var section = Configuration.GetSection("MySettings"); // this does not actually hold the settings
    services.Configure<MySettingsClass>(section); // this is a setup instruction, I can't actually get a MySettingsClass instance with the settings
    // ...
    // set up services
    services.AddSingleton(typeof(ISomething), typeof(ConcreteSomething));
}

I would need to actually read that section and decide what to register for ISomething (maybe a different type than ConcreteSomething).


回答1:


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<MySettings>(Configuration.GetSection(nameof(MySettings)));
        services.AddSingleton(Configuration);

        // ...

        var settings = Configuration.GetSection(nameof(MySettings)).Get<MySettings>();
        int maxNumberOfSomething = settings.MaxNumberOfSomething;

        // ...
    }

    // ...
}



回答2:


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; }

    ...
}



回答3:


You can access appsettings.json values by Configuration["ConfigSection:ConfigValue"])

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

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<MyContext>(o => 
            o.UseSqlServer(Configuration["AppSettings:SqlConn"]));
    }
}

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "System": "Information",
      "Microsoft": "Warning"
    }
  },
  "AppSettings": {
    "SqlConn": "Data Source=MyServer\\MyInstance;Initial Catalog=MyDb;User ID=sa;Password=password;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;"
  }
}



来源:https://stackoverflow.com/questions/40470556/actually-read-appsettings-in-configureservices-phase-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!