我不相信有一个内置的DI 方法来获取命令行参数 - 但可能是处理命令行参数的原因是您的主机应用程序的责任,并且应该在 via 等中传递主机/环境IConfiguration
信息IOptions
。
无论如何,只需定义您自己的注射剂:
public interface IEntrypointInfo
{
String CommandLine { get; }
IReadOnlyList<String> CommandLineArgs { get; }
// Default interface implementation, requires C# 8.0 or later:
Boolean HasFlag( String flagName )
{
return this.CommandLineArgs.Any( a => ( "-" + a ) == flagName || ( "/" + a ) == flagName );
}
}
/// <summary>Implements <see cref="IEntrypointInfo"/> by exposing data provided by <see cref="System.Environment"/>.</summary>
public class SystemEnvironmentEntrypointInfo : IEntrypointInfo
{
public String CommandLine => System.Environment.CommandLine;
public IReadOnlyList<String> CommandLineArgs => System.Environment.GetCommandLineArgs();
}
/// <summary>Implements <see cref="IEntrypointInfo"/> by exposing provided data.</summary>
public class SimpleEntrypointInfo : IEntrypointInfo
{
public SimpleEntrypointInfo( String commandLine, String[] commandLineArgs )
{
this.CommandLine = commandLine ?? throw new ArgumentNullException(nameof(commandLine));
this.CommandLineArgs = commandLineArgs ?? throw new ArgumentNullException(nameof(commandLineArgs));
}
public String CommandLine { get; }
public IReadOnlyList<String> CommandLineArgs { get; }
}
//
public static class Program
{
public static async Task Main( String[] args )
{
await Host.CreateDefaultBuilder( args )
.UseContentRoot(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))
.ConfigureServices((context, services) =>
{
services.AddHostedService<ConsoleHostedService>();
services.AddSingleton<IEntrypointInfo,SystemEnvironmentEntrypointInfo>()
})
.RunConsoleAsync();
}
对于自动化单元和集成测试,请使用SimpleEntrypointInfo
.