SHARE:

Building a Windows service with Worker Services and .NET Core 3.1, part 1: Introduction

Introduction

ASP.NET Core 3 brings a very interesting new feature: Worker Service. What is a Worker Service? It’s an ASP.NET Core template that allows you to create hosted long-running background services.
These background services implement the IHostedService interface, so they are called “hosted services”. What is interesting is that dependency injection is available natively, which was not the case with a Windows Service created with TopShelf.
They can be deployed as a Windows service but also Linux daemons.
In this article we will see how to create and deploy a Worker Service as a Windows Service

Create a Worker Service

To create a Worker Service, select in Visual Studio 2019 Worker Service then the desired version of ASP.NET Core (I recommend ASP.NET Core 3.1)

The default template looks like this:

Program.cs:

Worker.cs:

appsettings.json:

As you can see, this is very basic. This template doen’t implement all BackgroundService methods, StartAsync, StopAsync and Dispose are missing. Your new Worker Service should look like this:

Deploy a Worker Service as a Windows service

First thing to do is to install this package, because it’s not installed by default in the ASP.NET Core 3 Worker Service template:

Once done add UseWindowsService extension method on IHostBuilder like this:

Your project is now ready to deploy.

Let’s see now how we can deploy you Windows Service.

In this series of example the Windows service will take the name of the Worker Service class

There are two ways:

  • Using sc.exe Tool
  • Publishing an exe file

Step 1: Publish the Worker service

Step 2: Deploy and start with sc utility

Step 3: Stop and delete with sc utility

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: