获取 .NET Core Worker 服务 CommandLineConfigurationProvider 参数

Sha*_*ggy 3 .net-core

我创建一个 .NET Core Worker Service 应用程序,需要将命令行参数传递到应用程序中。我可以在通过 IConfiguration 配置 > 提供程序 > CommandLineConfigurationProvider 进行调试时看到参数,但不知道如何对其进行编码以获取参数。

任何帮助表示赞赏。

Gui*_*ndi 7

如果您有一个config提供的对象,IConfiguration您只需使用config.GetValue<string>("myvaluename")。

例如:

public static IHostBuilder CreateHostBuilder(string[] args)
{
    return new HostBuilder()
        .ConfigureAppConfiguration((context, cfg) =>
        {
            cfg.AddCommandLine(args);
        });
}
Run Code Online (Sandbox Code Playgroud)

获取配置:

static void Main(string[] args)
{
    using var host = CreateHostBuilder(args).Build();
    var config = host.Services.GetRequiredService<IConfiguration>();
    var myvalue = config.GetValue<string>("myvalue");
    // .... myvalue may be null if not specified
}
Run Code Online (Sandbox Code Playgroud)

最后,您像这样调用您的程序:

myprogram.exe --myvalue abcd
Run Code Online (Sandbox Code Playgroud)

CommandLineConfigurationProvider是非常基本的,因此它不支持复杂的模式,例如二元选项(存在/不存在)等。


som*_*men 5

您可以使用:https://learn.microsoft.com/en-us/dotnet/api/system.environment.getcommandlineargs ?view=netcore-3.1

获取命令行参数。

环境是静态的,因此您可以从任何地方访问它。

Environment.GetCommandLineArgs 
Run Code Online (Sandbox Code Playgroud)