Home > Enterprise >  Start arguments for Windows Background Service in .NET
Start arguments for Windows Background Service in .NET

Time:06-26

I am making a Windows Service using .NET's BackgroundService abstract class (similar to the one in Windows service config

Event log

CodePudding user response:

Create a class derived from ServiceBase to receive parameters and implement 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.

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