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.
