如何为后台服务传递参数?

9

我了解了ASP.NET Core 2.2,并发现有关于通用主机的参考资料。

我尝试按照示例创建带有backgroundService的控制台应用程序:https://github.com/aspnet/AspNetCore.Docs/tree/master/aspnetcore/fundamentals/host/generic-host/samples/

var param = Console.ReadLine();

var host = new HostBuilder().ConfigureServices((hostContext, services) =>
{
   services.AddHostedService<MyCustomSerivce>();
}

问题在于如何从命令行中传递参数(在我的情况下是“param”),以指定特定后台服务中的内部逻辑。

在高层次上,您应该使用内置的配置系统并将命令行参数添加到配置中。然后,服务可以通过 DI 获取配置对象。 - juunas
1个回答

9

为了解决服务问题,您需要将参数注册到服务集合中。

  1. Service for storing the parameter

    public class CommandLineArgs
    {
        public string Args { get; set; }
    }
    
  2. Register the parameter

    public class Program
    {
        public static async Task Main(string[] args)
        {
            var param = Console.ReadLine();
    
            var host = new HostBuilder()
                .ConfigureHostConfiguration(configHost =>
                {
                    configHost.SetBasePath(Directory.GetCurrentDirectory());
                    configHost.AddJsonFile("hostsettings.json", optional: true);
                    configHost.AddEnvironmentVariables(prefix: "PREFIX_");
                    configHost.AddCommandLine(args);
                })
                .ConfigureAppConfiguration((hostContext, configApp) =>
                {
                    configApp.AddJsonFile("appsettings.json", optional: true);
                    configApp.AddJsonFile(
                        $"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", 
                        optional: true);
                    configApp.AddEnvironmentVariables(prefix: "PREFIX_");
                    configApp.AddCommandLine(args);
                })
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddSingleton(new CommandLineArgs { Args = param });
                    services.AddHostedService<LifetimeEventsHostedService>();
                    services.AddHostedService<TimedHostedService>();
                })
                .ConfigureLogging((hostContext, configLogging) =>
                {
                    configLogging.AddConsole();
                    configLogging.AddDebug();
                })
                .UseConsoleLifetime()
                .Build();
    
            await host.RunAsync();
        }
    }
    
  3. Resolve service

    internal class TimedHostedService : IHostedService, IDisposable
    {
        private readonly ILogger _logger;
        private Timer _timer;
        private readonly IConfiguration _configuration;
        private readonly CommandLineArgs _commandLineArgs;
        public TimedHostedService(ILogger<TimedHostedService> logger
            , IConfiguration configuration
            , CommandLineArgs commandLineArgs)
        {
            _logger = logger;
            _configuration = configuration;
            _commandLineArgs = commandLineArgs;
        }       
    }
    

1
在这里使用 configApp.AddCommandLine(args) 的意义是什么? - El Mac
我不确定TimedHostedService是否会启动。 - Renascent
对于@ElMac的问题,它将成为IConfiguration实例的一部分,如果我们有自己的配置文件模型,那么这个命名参数也将解析为相应的属性和值。比如,我们使用appName.exe --Param1 "Value1",它将解析为绑定模型,只要它们有public string Param1 {get; set;}作为其中一个属性。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接