A new type of application template called “Worker Service” was introduced in .NET Core 3 (still in preview as writing this). This is the new way of writing Windows Service or Linux Daemons in .NET Core.
Previously, we can create these services in .NET Core 2.1 using IHostedService. You can simply create a console app in .NET Core 2.1 and use the top-shelf NuGet package (there are other ways too) to listen for start and stop signals from WindowsService. You are all done. Then why worker service?
This application type intends to provide an entry point for long-running services in .NET Core. The perfect use case is any long-running background processing to handle the messages from any queues, or if you are wanting to check the health of your apps. A worker service is a straightforward framework for these kinds of use cases. You can deploy it either as a Windows service or as a Linux daemon. Here is the step-by-step walkthrough to create a simple Worker Service as Windows Service and Linux Daemons.
Download sample source here.
If you can’t see .NET Core 3.0 in the dropdown, you need to tell VS to use the preview SDKs. Open Tools > Options in the menu bar. Open the Projects and Solutions node. Open the .NET Core tab. Check the box for Use previews of the .NET Core SDK. Select OK
Please note that the option Use previews of the .NET Core SDK have moved under Tool -> Options -> General -> Preview SDK
Please check the compatibility between the preview SDK and the Visual Studio 2019 version if you are missing the Worker Service template.
Program.CS
The Host is responsible for application startup and lifetime management. CreateDefaultBuilder creates this runtime host to run the application. CreateDefaultBuilder does a few things: configuring the Kestrel server, setting the root directory, load app configuration (appsettings.json, appsettings.{Environment}.json), and configuring logging.
Worker.cs
This is the background worker which does the actual job.
To run as a Windows Service, we need our worker to listen for the start and stop signals from ServiceBase, the .NET type that exposes the Windows Service systems to .NET applications. To do this we want to add Microsoft.Extensions.Hosting.WindowsService NuGet package.
If you get any error while installing, there is a version mismatch between your NuGet package and to .NET Core SDK. Make sure you have the same preview version for both.
Add the UseWindowsService() call to the host builder.
Now we can use sc.exe utility to deploy it as a Windows server.
Add Microsoft.Extensions.Hosting.Systemd NuGet package (please note that you need .NET Core SDK Preview7+ for this).
Add UseSystemd() call to host builder.
Set up as daemon on Linux.
Legal Stuff