Skip to content

Instantly share code, notes, and snippets.

@hasmukhlalpatel
Created February 10, 2025 10:41
Show Gist options
  • Select an option

  • Save hasmukhlalpatel/3043a64c63abb826dfa272ed9f2cfbf8 to your computer and use it in GitHub Desktop.

Select an option

Save hasmukhlalpatel/3043a64c63abb826dfa272ed9f2cfbf8 to your computer and use it in GitHub Desktop.
How to add more configuration files to a web application? how to override default configuration files?

Config load order

Copied from How to add more configuration files to a web application?

Configuration is roughly loaded in this order:

  1. appsettings.json
  2. appsettings{Environment}.json
  3. Environment variables
  4. Command line arguments

override default config

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.InsertBefore(c =>
{
    c.AddJsonFile("MyInitialSource.json", optional: true);
});

var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

public static class ConfigurationExtensions 
{
    public static ConfigurationManager InsertBefore(this ConfigurationManager config, Action<ConfigurationManager> action)
    {
        // Get all existing sources and make a copy
        var existing = config.Sources.ToArray();
        // Clear theses sources
        config.Sources.Clear();
        // Mutate configuration
        action(config);
        // Add the older sources back
        foreach (var s in existing)
        {
            config.Sources.Add(s);
        }
        return config;
    }
}

You can mutate the list of sources, here's an example of inserting it first.

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.InsertBefore(c =>
{
    c.AddJsonFile("MyInitialSource.json", optional: true);
});

var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

public static class ConfigurationExtensions 
{
    public static ConfigurationManager InsertBefore(this ConfigurationManager config, Action<ConfigurationManager> action)
    {
        // Get all existing sources and make a copy
        var existing = config.Sources.ToArray();
        // Clear theses sources
        config.Sources.Clear();
        // Mutate configuration
        action(config);
        // Add the older sources back
        foreach (var s in existing)
        {
            config.Sources.Add(s);
        }
        return config;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment