Search code examples
c#asp.net.netdependency-injectionasp.net-core-mvc

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>();
    ....
}

Solution

  • 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.