如何传递BackgroundService的参数? [英] How to pass parameters for BackgroundService?

查看:166
本文介绍了如何传递BackgroundService的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解了ASP.net core 2.2,并找到了有关通用主机的参考.

I read about ASP.net core 2.2 and I found reference about generic host.

在以下示例中,我尝试使用backgroundService创建控制台应用程序: https://github.com/aspnet/AspNetCore.Docs/tree/master/aspnetcore/fundamentals/host/generic-host/samples/

I tried to create console app with backgroundService under example: 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")中传递参数,该参数将在特定的后台服务中指定内部逻辑.

The problem is how can be passed argument from command line (in my case 'param'), that will specified internal logic in particular background service.

推荐答案

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

For resolving service, you need to register the parameters into service collection.

  1. 用于存储参数的服务

  1. Service for storing the parameter

public class CommandLineArgs
{
    public string Args { get; set; }
}

  • 注册参数

  • 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();
        }
    }
    

  • 解决服务

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

  • 这篇关于如何传递BackgroundService的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆