我需要在ASP.NET Core 1.0 Web应用程序中的ConfigureServices
方法中设置一些依赖项(服务)。
问题是,基于新的JSON配置,我需要设置服务或其他服务。
我似乎无法真正阅读应用程序生命周期的ConfigureServices
阶段中的设置:
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));
}
我需要实际阅读该部分并决定注册ISomething
(可能是与ConcreteSomething
不同的类型)。
这就是你可以在appSettings.json
方法中从ConfigureServices
获取类型化设置的方法:
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;
// ...
}
// ...
}
从ASP.NET Core 2.0开始,我们在构建Program
实例时在WebHost
类中进行配置设置。此类设置的示例:
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);
})
其中,这允许直接在Startup
类中使用配置,通过构造函数注入获取IConfiguration
的实例(谢谢,内置DI容器):
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
...
}
您可以通过Configuration["ConfigSection:ConfigValue"])
访问appsettings.json值
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;"
}
}