Blog

Filter posts by Category Or Tag of the Blog section!

Running worker service as windows service

Wednesday, 24 November 2021

Worker Service in dotnet lets you create a long-running service in a CMD environment by using  BackgroundService, which is an implementation of IHostedService. Rather than that it provinces the capability to run it as a windows service. In order to do that create a ServiceWorker project in visual studio and install the following package:

 

dotnet add package Microsoft.Extensions.Hosting.WindowsServices --version 7.0.0

 

Now modify the default program class to use windows service: 



 

using WorkerService1;

IHost host = Host.CreateDefaultBuilder(args)
     .UseWindowsService(options =>
     {
         options.ServiceName = "My Windows Service";
     })
    .ConfigureServices(services =>
    {
        services.AddHostedService<Worker>();
    })
    .Build();

await host.RunAsync();

 

The worker is the default background service of the Service Worker in vs template with the following definition:

 

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

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                await Task.Delay(1000, stoppingToken);
            }
        }
    }


We just added UseWindowsService() with a given name. That’s it about the required code to run in windows service. For publishing the worker service, you need to

  1. Set the configuration as Release/ Any CPU 
  2. Set the Deployment as self contained (recommended)
  3. Set the target runtime based on your target machine (for me it’s a windows server)

 

You can check the Product Single File and Enable ReadyToRun compilation as true to make only a single file as .exe

 

 

After transferring the file to the target machine, if its windows you can run the following command to create a windows service:

 

sc.exe create "My Service" binpath="C:\service\MyService.exe"

 

Now you can refer to the services of your windows machine and run the service manually.
 

Category: Software

Tags: Dot Net

comments powered by Disqus