How to set hosting environment name for .NET Core console app using Generic Host (HostBuilder)

You can set the environment from the command line variables via the ConfigureHostConfiguration extension method.

Set up the configuration for the builder itself. This will be used to initialize the Microsoft.Extensions.Hosting.IHostEnvironment for use later in the build process.

var hostBuilder = new HostBuilder()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .ConfigureHostConfiguration(configurationBuilder => {
        configurationBuilder.AddCommandLine(args);
    })
    .ConfigureAppConfiguration((hostingContext, cfg) =>
    {
        // ...

        var env = hostingContext.HostingEnvironment;
        Console.WriteLine(env.EnvironmentName); // Test
        // ...
    });
    
    // ...

    hostBuilder.Build();

In Visual Studio, you configure the application arguments with the same ones as being used by dotnet run which is --environment,
e.g. dotnet run --environment Test.

Without this application argument, the hosting environment defaults back to Production.

enter image description here


To pick up the hosting environment from environment variables, you can also add:

.ConfigureHostConfiguration(config =>
{
    config.AddEnvironmentVariables();
})

Then use Environment environment variable to pass the actual environment.

Tags:

C#

.Net Core