What is the right way to configure services for different environments?
For example I want to add FakeService to services collection for DEV configuration and RealService for Release configuration.
public void ConfigureServices(IServiceCollection services)
{
/* Need to check environment */
services.AddSingleton<IService, FakeService>();
....
}
MVC 6 has a value that defines what environment it is, this can be set by the environment variable ASPNET_ENV. You can grab that value from IHostingEnvironment:
public void ConfigureServices(IServiceCollection services)
{
var env = services.BuildServiceProvider().GetRequiredService<IHostingEnvironment>();
if (env.IsDevelopment())
Console.WriteLine("Development");
else if (env.IsProduction())
Console.WriteLine("Production");
else if (env.IsEnvironment("MyCustomEnvironment"))
Console.WriteLine("MyCustomEnvironment");
}
You can set the value in VS2015 on your project by Right-click > Properties > Debug > Environment Variables:

Here's some more info on configuring with environment variables.
It's just a matter of reading this from your configuration file, and making a decision in code accordingly:
bool isDev = Boolean.Parse(ConfigurationManager.AppSettings["IsDev"]);
if (isDev) {
services.AddSingleton<IService, FakeService>();
} else {
services.AddSingleton<IService, RealService>();
}
Another option is to use compiler directives:
if #DEBUG
services.AddSingleton<IService, FakeService>();
#else
services.AddSingleton<IService, RealService>();
#endif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With