简体   繁体   English

在 .NET 中启动 Windows 后台服务的参数

[英]Start arguments for Windows Background Service in .NET

I am making a Windows Service using .NET's BackgroundService abstract class (similar to the one in this tutorial by Microsoft) but I can't seem to figure out how to get start arguments passed to the service using the Windows Services app.我正在使用 .NET 的BackgroundService抽象类(类似于 Microsoft 在本教程中的类)创建 Windows 服务,但我似乎无法弄清楚如何使用 Windows 服务应用程序将启动参数传递给服务。 Can someone tell me how to get the arguments I pass in there or what I should be doing?有人可以告诉我如何获得我在那里传递的论点或我应该做什么吗?

You have to pass through the args from Main :您必须从Main传递参数:

public static async Task Main(string[] args)
{
    IHost host = Host.CreateDefaultBuilder(args)
        .ConfigureLogging(options =>
        {
            options.ClearProviders();
            options.AddEventLog();
            options.AddConsole();
        })
        .UseWindowsService(options =>
        {
            options.ServiceName = "WorkerServiceTestArgs";
        })
        .ConfigureServices(services =>
        {
            services.AddSingleton(new MyArgsService(args));
            services.AddHostedService<Worker>();
        })
        .Build();

    await host.RunAsync();
}

Your worker then has a dependency on your service:然后,您的工作人员依赖于您的服务:

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly MyArgsService _myArgsService;

    public Worker(ILogger<Worker> logger, MyArgsService myArgsService)
    {
        _logger = logger;
        _myArgsService = myArgsService;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            _logger.LogInformation("Args: {args}", string.Join(";", _myArgsService.GetArgs()));

            await Task.Delay(1000, stoppingToken);
        }
    }
}

eg with this simple Service:例如,使用这个简单的服务:

public class MyArgsService
{
    private readonly string[] _args;

    public MyArgsService(string[] args)
    {
        _args = args;
    }

    public string[] GetArgs()
    {
        return _args;
    }
}

Results:结果:

Windows 服务配置

事件簿

Create a class derived from ServiceBase to receive parameters and implement IHostLifetime .创建一个派生自ServiceBase的类以接收参数并实现IHostLifetime

public class MyServiceLifetime : ServiceBase, IHostLifetime
{
    protected override void OnStart(string[] args)
    {
        base.OnStart(args);
    }

    public public Task WaitForStartAsync(CancellationToken cancellationToken)
        => Task.CompletedTask;
    
    public Task StopAsync(CancellationToken cancellationToken)
        => Task.CompletedTask;
}

Replace this class with UseWindowsService .将此类替换为UseWindowsService

using IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddSingleton<IHostLifetime, MyServiceLifetime>();
        services.AddSingleton<JokeService>();
        services.AddHostedService<WindowsBackgroundService>();
    })
    .Build();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM