Search code examples
c#.netenvironmentapp-startup

Set Enviroment in WebApplication.CreateBuilder from configuration


So I'm trying to setup the webapp enviroment name according to the company deployment policy based on transformations of appsettings file during the pipeline deployment. We are using IWebHostEnvironment for reading the env and rootpath later in startup process.

But I'm running into the issue that I don't know how properly resolve. Is there any option to prebuild the configuration so that I can read value from it before creating new builder or this is the 'way' how to do it. To have one default pre-builder for configuration and than create regular one for the normal app. It looks like chicken-egg problem to me.

Other solution would be to read 'environment' from the configuration directly but doesn't look clean to me.

var configBuilder = WebApplication.CreateBuilder(args);
configBuilder.Configuration.SetupConfiguration(args);

var section = configBuilder.Configuration.GetSection("Hosting")["Environment"];

var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
    EnvironmentName = section
});

Solution

  • By default environment comes from environment variables (see the docs). If you really need to read the environment from config file then the approach with WebApplicationOptions is the way to go. You can improve it a bit by just reading the config, not using WebApplication.CreateBuilder for that:

    var cfgBuilder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile(...); // setup your config probably call cfgBuilder.SetupConfiguration(args)
    
    var cfg = cfgBuildeR.Build();
    
    var builder = WebApplication.CreateBuilder(new WebApplicationOptions
    {
        EnvironmentName = cfg.GetSection("Hosting")["Environment"]
    });