Search code examples
wpfconfigurationappsettings

How can we add new sections to appsettings after build?


I'm working on a WPF C# program that we want to customize based on its location. I'm using DI with IOptions and I've read through dozens of options for adding particular variations of configBuilder.AddJsonFile($"appsettings.{some_variation}.json"). My particular situation requires me to load a specific json file based on a setting in the main appsettings.json file. I can't get to it until after configBuilder.build(), can I? Can I add more sections after configBuilder.Build() runs?

    IConfigurationBuilder configBuilder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json");

    if (Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") != null
        && Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT").Length > 0)
        configBuilder.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")}.json");

So far, so good. But now I need settings that are specific to the site where it's used. In the main settings I have this

"Plant": {
    "Site": "0201",
    "Abbrev": "SAC"
}

and I'd like to add a new file appsettings.plc.SAC.json. I can't access the AppSettings.Plant.Abbrev until after configBuilder.Build() runs and I can't use AddJsonFile after that's done. On site it could use the Environment.MachineName.Substring(0,3), but that won't work during development. Maybe I should put the site info into launch options. I'm not sure if that's the best idea. Anyone have any other solutions? TIA, Mike


Solution

  • You could use another builder to parse the value before you actually configure your app:

    var abbrev = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build().GetSection("Plant")["Abbrev"];
    
    IConfigurationBuilder configBuilder = new ConfigurationBuilder()
    ...
    

    Or parse the file yourself somehow else. After all, it's just a text based configuration file.