首页 > 解决方案 > 如何为BackgroundService传递参数?

问题描述

我阅读了有关 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'),这将在特定的后台服务中指定内部逻辑。

标签: c#asp.net-core

解决方案


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

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

推荐阅读