Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register different services for different environments in ASP.NET MVC 6?

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>();
    ....
}
like image 860
Rover Avatar asked Oct 21 '25 11:10

Rover


2 Answers

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:

Environment variables

Here's some more info on configuring with environment variables.

like image 189
Stafford Williams Avatar answered Oct 23 '25 02:10

Stafford Williams


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
like image 33
Steven Avatar answered Oct 23 '25 02:10

Steven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!