在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")),
);
}
但是在netcoreapp2.0中,配置是在Program
中单独定义的。所以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")),
);
}
那么我如何在ConfigureServices()
中获取IConfigurationRoot
,以便我可以设置我的强类型Stuff1
和Stuff2
选项,以及其他内容,如连接字符串?
事实证明,它会自动注册到容器中,并且像这样可用:
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public readonly IConfiguration _configuration;
这对我有用,但我认为也可以使用IConfigurationRoot
.