Vaughan Reid's blog

Running a .NET Core HostedService as a Windows service

If you need to run your long running .NET Core worker application on a windows server, you can easily install it as a windows service with minimal changes.

Just add the following package.

Microsoft.Extensions.Hosting.WindowsServices

Then all you have to do is add UseWindowsService() to your host builder and its ready to use.


public static IHostBuilder CreateHostBuilder(string[] args) =>
	Host.CreateDefaultBuilder(args)
		.ConfigureServices((hostContext, services) =>
		{
			services.AddHostedService<Worker>();
		})
		.UseWindowsService();

I’m using the worker service template to show how to install it.

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

To install it just run the following command in a adminstrator cmd prompt.


sc create WorkerService binPath= "full_path_to_exe"