In my application I am using appsettings to load my configuration. I have the appsettings.json
:
{
"FileReader": {
"InputDirectory": "tmp"
}
}
I would like to have the option to override the value of InputDirectory
with a command line argument shorthand switch (e.g. -i
). I know I can override it via an environment variable named FileReader__InputDirectory
, but for the SwitchMappings in my Program.cs
I don't know what value would work. Here is my code:
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, builder) =>
{
builder
.AddJsonFile("appsettings.json", false, false)
.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", true, false)
.AddEnvironmentVariables()
.AddCommandLine(source =>
{
source.Args = args;
source.SwitchMappings = new Dictionary<string, string>()
{
{ "-i", "FileReader__InputDirectory" } // <-- what is the correct mapping here?
};
});
})
.ConfigureServices((context, services) =>
{
Console.WriteLine(context.Configuration.GetSection("FileReader")["InputDirectory"]);
services.AddHostedService<Worker>();
})
.Build();
When I am running dotnet run -i ./source/json
I would expect the printed out value to be source/json (the value from the argument) but what I get is tmp (the value from the appsettings.json
file).
If I try this without the nesting with a property on the appsettings root level it works just fine.