< p > < code > CreateDefaultBuilder 添加了 < code > CommandLineConfigurationProvider 到其配置提供程序中,但通常您不会直接访问它。相反,将一个 < code > IConfiguration 参数添加到您的 < code > ConsoleHostedService 构造函数中,您将自动从多个设置源接收设置,包括命令行参数:
internal sealed class ConsoleHostedService : IHostedService
{
public ConsoleHostedService(
IHostApplicationLifetime appLifetime,
IServiceProvider serviceProvider,
IConfiguration configuration)
{
// Get the value as a string
string argValueString = configuration["MyFirstArg"]
// Or if it's an integer
int argValueInt = configuration.GetValue<int>("MyFirstArg")
}
}
这需要您的命令行参数遵循如此定义的规定格式:
MyFirstArg=12345
/MyFirstArg 12345
--MyFirstArg 12345
然而...
如果您确实需要获取实际的命令行参数,并且不介意依赖于默认生成器的实现,可以进行以下操作:
创建一个自定义的CommandLineConfigurationProvider
类并公开其Data
和Args
属性:
public class ExposedCommandLineConfigurationProvider : CommandLineConfigurationProvider
{
public ExposedCommandLineConfigurationProvider(IEnumerable<string> args, IDictionary<string, string> switchMappings = null)
:base(args, switchMappings)
{
}
public new IDictionary<string, string> Data => base.Data;
public new IEnumerable<string> Args => base.Args;
}
然后在您的主程序中,将其添加到现有配置提供程序列表中:
internal sealed class Program
{
private static async Task Main(string[] args)
{
await Host.CreateDefaultBuilder(args)
.UseContentRoot(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))
.ConfigureAppConfiguration(config => config
.Add(new ExposedCommandLineConfigurationSource { Args = args }))
.ConfigureServices((context, services) => services
.AddHostedService<SchedulerWorker>())
.RunConsoleAsync();
}
}
最后,从提供给您的IConfiguration中挖掘出您的参数提供程序,并传递给ConsoleHostedService。
internal sealed class ConsoleHostedService : IHostedService
{
public ConsoleHostedService(
IHostApplicationLifetime appLifetime,
IServiceProvider serviceProvider,
IConfiguration configuration)
{
if (configuration is ConfigurationRoot configRoot)
{
var provider = configRoot.Providers.OfType<ExposedCommandLineConfigurationProvider>().Single();
var rawArgs = provider.Args;
var namedArgs = provider.Data;
}
else
{
}
}
}
但是对于一些本来可以很简单完成的事情,这似乎需要花费大量的工作量(并且可能会因为默认构建器实现的任何更改而导致破坏)。
System.Environment.GetCommandLineArguments()
是一个用于获取命令行参数的方法。 - DaiCreateDefaultBuilder(args)
恰好在main
的args
处调用。另外,Environment.CommandLine
是一个单块字符串,当然我可以使用空格拆分它,但如果我得到了原始的 OS 数组,它会 更少出错,并且更兼容。 - g.pickardou