Until the introduction of the Worker Service in .NET Core 3 I always used TopShelf to turn my console application into a windows service.
Let’s see how we can do this using the built-in packages…
- Start by creating a new worker project from the command line(or open Visual Studio and search for ‘worker’ in the available templates)
dotnet new worker
- Now add the following nuget package to our project:
Install-Package Microsoft.Extensions.Hosting.WindowsServices
- Next we have to modify our program.cs file and add a “UseWindowsService()”.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static IHostBuilder CreateHostBuilder(string[] args) => | |
Host.CreateDefaultBuilder(args) | |
.ConfigureServices((hostContext, services) => | |
{ | |
services.AddHostedService<Worker>(); | |
}).UseWindowsService(); |
- That’s it!
Of course, you don’t have to believe me like that so let’s try to install our newly created windows service. This can be done through the standard Windows Service installer:
sc create ExampleService BinPath=C:\Projects\test\ExampleService\bin\Debug\netcoreapp3.1>ExampleService.exe
Now open up your services window and have a look: