•
In this blog post, we will walk through the steps to run a .NET Core application as a Windows Service, including setting up your project and configuring it for service management.
Before we begin, make sure you have the following:
.NET Core provides a built-in template to create Worker Services that are designed to run in the background as Windows Services. To create a new Worker Service:
Open your terminal (Command Prompt or PowerShell) and run the following command to create a new Worker project:
This command will generate a new Worker Service project with the necessary setup to run as a Windows Service.
Inside the
Worker
class, you’ll find an example ExecuteAsync
method that runs in the background when the service starts. You can modify this method to include the logic of your application.For instance, if you're running a background task, you can modify the
ExecuteAsync
method as follows:To run the application as a Windows Service, you need to modify the
Program.cs
file to include the UseWindowsService
method. This will configure the worker to run as a Windows Service when deployed to a Windows machine.Modify
Program.cs
as follows:To deploy your Worker Service, you need to publish it to a folder. Run the following command in your project directory:
This command will generate a self-contained executable that can run on any Windows machine without requiring the .NET runtime to be installed.
To install your application as a Windows Service, you’ll need to use the
sc
command or create a service configuration script using PowerShell.Here’s how to install the service using the
sc
command:Open a PowerShell window as Administrator.
Run the following command to create the service:
Make sure to replace
"C:\path\to\your\published\app\MyWindowsService.exe"
with the actual path to your published application.To start the service:
To stop the service:
To remove the service:
Once the service is installed, you can verify that it’s running by checking the Windows Service Manager or by using the
sc query
command:You should see the status of the service, and it should be running. Additionally, you can check the logs created by your Worker Service, as configured by the
ILogger
service.Running a .NET Core application as a Windows Service provides a robust and reliable way to manage long-running background processes. By following the steps above, you can create, deploy, and manage your application as a service on Windows, making it easier to handle tasks like auto-starting on boot and running without a user interface.
As always, consider testing your services thoroughly and managing their lifecycle properly for production environments. With .NET Core's flexibility, you can create powerful background applications that seamlessly integrate into the Windows ecosystem.
0 comments
Discover the latest insights and trends from our blog.