如何传递BackgroundService的参数?

时间:2019-06-03 08:59:58

标签: c# asp.net-core

我了解了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”)传递参数,该参数将在特定的后台服务中指定内部逻辑。

1 个答案:

答案 0 :(得分:0)

要解析服务,您需要将参数注册到服务集合中。

  1. 用于存储参数的服务

    public class CommandLineArgs
    {
        public string Args { get; set; }
    }
    
  2. 注册参数

    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. 解决服务

    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;
        }       
    }