•
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:
dotnet new worker -n MyWindowsService
cd MyWindowsService
To enable the app to run as a Windows Service, install the following NuGet package:
dotnet add package Microsoft.Extensions.Hosting.WindowsServices
Edit
Program.cs
to detect if the app is running as a Windows Service and configure the host accordingly:
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System.Diagnostics; using System.IO; HostApplicationBuilder builder = Host.CreateApplicationBuilder(args); builder.Services.AddHostedService<Worker>(); if (OperatingSystem.IsWindows()) { builder.Host.UseWindowsService(); } var app = builder.Build(); app.Run();
Now publish the application as a folder-deployable app:
dotnet publish -c Release -o C:\Services\MyWindowsService
Use the
sc.exe
tool to create the service from an elevated command prompt:
sc create MyWindowsService binPath= "C:\Services\MyWindowsService\MyWindowsService.exe"
Then start the service:
sc start MyWindowsService
When running as a Windows Service, standard console logs won’t appear. You should configure a file-based logger or use Windows Event Logs to capture logs.
To stop and remove the service when no longer needed:
sc stop MyWindowsService sc delete MyWindowsService
Running a .NET Core Worker Service as a Windows Service is a reliable and production-ready solution for background tasks, scheduled jobs, or daemon-style operations. With just a few modifications and configurations, your app can seamlessly integrate into Windows service infrastructure.
In future articles, we’ll explore how to add logging, health checks, and service recovery options to further improve your background services.
0 comments
Discover the latest insights and trends from our blog.
Sustainable living involves making intentional choices to preserve natural resources, reduce pollution, and support long-term ecological balance through practices like ...
Poor software architecture leads to 5deep, hard-to-fix bugs. This article explores causes, examples, and best practices to build scalable, maintainable, bug-resistant systems. ...
Explore key software design principles like SOLID, DRY, KISS, and design patterns to build clean, scalable, and maintainable applications. Perfect for modern developers. ...