在我的应用程序中,我使用应用程序设置来加载我的配置.我有appsettings.json
:
{
"FileReader": {
"InputDirectory": "tmp"
}
}
我希望 Select 用命令行参数速记switch (例如-i
)覆盖值InputDirectory
.我知道我可以通过一个名为FileReader__InputDirectory
的环境变量来覆盖它,但是对于我的Program.cs
中的SwitchMappings,我不知道什么值可以工作.以下是我的代码:
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();
当我运行dotnet run -i ./source/json
时,我希望打印输出的值是source/json(来自参数的值),但我得到的是tmp(来自appsettings.json
文件的值).
如果我在不嵌套应用程序设置根级别上的属性的情况下try 这样做,它会工作得很好.