Override nested appsettings configuration with command line argument shorthand switch – C#

by
Ali Hasan
.net-4.6 asp.net-core-6.0 asp.net-web-api c#

Quick Fix: Use : as the delimiter and pass the configuration through the CLI parameter:

dotnet run --FileReader:InputDirectory=./source/json

The Problem:

In an application using nested appsettings configuration, you want to override a nested configuration value using a command-line argument shorthand switch. The existing code attempts to map the switch to the correct configuration property but fails. Determine the correct mapping and provide the solution to override the nested property value with the command-line argument.

The Solutions:

Solution 1: Use delimiter

Use : as a delimiter in the SwitchMappings dictionary:

source.SwitchMappings = new Dictionary<string, string>()
{
     { "-i", "FileReader:InputDirectory" } // ":" delimiter for nested configuration
};

Note that __ substitution is specifically for environment variables.

Solution 2: Find and change the existing source

It seems the real question is how to add a new argument mapping, not how to override settings.

All config sources are available through the ConfigurationBuilder.Sources list. The configuration code could find the existing source and change its mapping :

.ConfigureAppConfiguration((context, builder) =&gt;
{
    var cliSource=builder.Sources.OfType&lt;CommandLineConfigurationSource&gt;();
    if(cliSource!=null)
    {
        cliSource.SwitchMappings=new Dictionary&lt;string, string&gt;()
                {
                    { &quot;-i&quot;, &quot;FileReader:InputDirectory&quot; }
                };
    }
}

Q&A

What is the correct mapping in SwitchMappings for nested appsettings configuration?

Use : as delimiter: -i maps to FileReader:InputDirectory.

Is there another way to override settings without modifying ConfigureAppConfiguration?

Remove the section and use --FileReader:InputDirectory in the command line.