[英]Porting configuration options from netcoreapp1.1 to netcoreapp2.0
In netcoreapp1.1 my config was defined in the Startup
, which had this: 在netcoreapp1.1中,我的配置是在
Startup
中定义的,它具有以下功能:
public Startup(IHostingEnvironment env)
{
_configuration =
new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
.Build();
}
private readonly IConfigurationRoot _configuration;
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<Stuff1>(_configuration.GetSection("stuff1"));
services.Configure<Stuff2>(_configuration.GetSection("stuff2"));
services.AddDbContext<Context>(options =>
options.UseSqlite(_configuration.GetConnectionString("DefaultConnection")),
);
}
But in netcoreapp2.0 config is defined separately in Program
. 但是在netcoreapp2.0中,config是在
Program
单独定义的。 So Startup
now only has this: 因此,
Startup
现在只有这样:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
var configuration = //??? how do I get this?
services.AddOptions();
services.Configure<Stuff1>(configuration.GetSection("stuff1"));
services.Configure<Stuff2>(configuration.GetSection("stuff2"));
services.AddDbContext<Context>(options =>
options.UseSqlite(configuration.GetConnectionString("DefaultConnection")),
);
}
So how do I get the IConfigurationRoot
in ConfigureServices()
, so that I can setup my strongly typed Stuff1
and Stuff2
options, and other stuff like the connections string? 那么,如何在
ConfigureServices()
获得IConfigurationRoot
,以便可以设置强类型化的Stuff1
和Stuff2
选项以及其他诸如连接字符串之类的东西?
Turns out it's automatically registered with the container, and is available like this: 原来它是自动在容器中注册的,并且可以这样使用:
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public readonly IConfiguration _configuration;
This works for me, but I think it's also possible to use IConfigurationRoot
. 这对我有用,但是我认为也可以使用
IConfigurationRoot
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.