.net-core.net-8.0

How to switch between environments in a self-contained .NET 8 app?


I have a .NET 8 app that is self-contained and published, I'm trying to switch between the multiple environments configurations using command line:

c:\path\app.exe --environment Development

but it's not working, it always defaults to Production.

I'm using

var builder = Host.CreateApplicationBuilder(args);

Solution

  • Turns out I have to manually set the env variable passed in args, so in Program.cs:

    Environment.SetEnvironmentVariable("DOTNET_ENVIRONMENT", args[1]);

    and after that you read it elsewhere by:

    Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")

    The args are passed like this: exename.exe --environment Production