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中的决策流程。但这似乎是一种不太好的解决办法。
我知道环境在.Net Core中是一种一等概念。 是否有一种方法可以直接从appsetting.json中完成这个操作?
实现此操作的最佳实践是什么?