In the StartUp class's Configure method of ASP.Net MVC Core, "IHostingEnvironment env" is passed in via Dependency Injection. And decisions can be made based on the environment. For example,
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
In ConfigureServices, I want to do something like this to pick the correct Connection string. Something like:
if (env.IsDevelopment())
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
else if (env.IsStaging())
{
// Add Staging Connection
}
else
{
// Add Prod Connection
}
But "IHostingEnvironment env" is not passed in to the ConfigureServices method by default. So I modify the signature from:
public void ConfigureServices(IServiceCollection services)
to
public void ConfigureServices(IServiceCollection services, IHostingEnvironment env)
and in ConfigureServices put:
if (env.IsDevelopment())
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
else if (env.IsStaging())
{
// Add Staging Connection
}
else
{
// Add Prod Connection
}
So now when I run I get this error message:
"The ConfigureServices method must either be parameterless or take only one parameter of type IServiceCollection."
ConfigureServices() won't take in the IHostingEnvironment var.
But "Startup.StartUp(IHostingEnvironment env)" does. I thought about adding a StartUp class field and setting it to the correct environment from Startup() and then using that field to make the decision flow in ConfigureServices. But this seems like a hack.
I know environment is a first class concept in .Net Core. Is there a way to do this straight from appsetting.json?
What is the best practice to accomplish this?