【发布时间】:2016-12-26 14:03:02
【问题描述】:
在 ASP.Net MVC Core 的 StartUp 类的 Configure 方法中,“IHostingEnvironment env”是通过依赖注入传入的。 并且可以根据环境做出决策。例如,
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
在 ConfigureServices 中,我想做这样的事情来选择正确的连接字符串。 比如:
if (env.IsDevelopment())
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
else if (env.IsStaging())
{
// Add Staging Connection
}
else
{
// Add Prod Connection
}
但默认情况下“IHostingEnvironment env”并没有传递给 ConfigureServices 方法。 所以我从以下位置修改签名:
public void ConfigureServices(IServiceCollection services)
到
public void ConfigureServices(IServiceCollection services, IHostingEnvironment env)
并在 ConfigureServices 中放置:
if (env.IsDevelopment())
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
else if (env.IsStaging())
{
// Add Staging Connection
}
else
{
// Add Prod Connection
}
所以现在当我运行时,我会收到以下错误消息:
“ConfigureServices 方法必须要么是无参数的,要么只接受一个 IServiceCollection 类型的参数。”
ConfigureServices() 不会接受 IHostingEnvironment 变量。
但是“Startup.StartUp(IHostingEnvironment env)”可以。 我考虑过添加一个 StartUp 类字段并将其从 Startup() 设置为正确的环境,然后使用该字段在 ConfigureServices 中进行决策流程。但这似乎是一个 hack。
我知道环境是 .Net Core 中的一流概念。 有没有办法直接从 appsetting.json 做到这一点?
实现这一目标的最佳做法是什么?
【问题讨论】: