2

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
});
freshbm
  • 5,540
  • 5
  • 46
  • 75
  • `transformations of appsettings file` appsettings isn't getting transformed. It doesn't need to. There's nothing special about those JSON files. Configuration settings come from multiple sources and later sources override previous ones. An `appsettings.Production.json` file doesn't transform `appsettings.json`, it *overrides* its settings, only because it's registered after them. Environment variables and command line settings in turn override the settings that came from the `appsettins` files. – Panagiotis Kanavos Nov 11 '22 at 10:38
  • 1
    The easy way to override settings in a CI/CD pipeline or production is to specify the overrides as environment variables or command-line settings – Panagiotis Kanavos Nov 11 '22 at 10:38

1 Answers1

2

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"]
});
Guru Stron
  • 102,774
  • 10
  • 95
  • 132