TechBuzzPro

Create a Windows Service with .NET Core: Step-by-Step

· 6 min read · Windows & PC

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To create a Windows Service in .NET Core, you must use the Worker Service template and install the Microsoft.Extensions.Hosting.WindowsServices NuGet package, which allows the application to communicate with the Windows Service Control Manager (SCM). This process converts a standard console application into a background process that can start automatically when the computer boots, run without a user logged in, and be managed via the Services snap-in.

What You'll Need

  • Visual Studio 2022 (or the latest stable version) with the .NET desktop development workload installed.
  • .NET 6, .NET 7, or .NET 8 SDK.
  • Administrative privileges on the Windows machine where the service will be installed.
  • The Windows Command Prompt or PowerShell running as Administrator.

Step-by-Step

  1. Create the Project: Open Visual Studio and select Create a new project. In the search bar, type "Worker" and select the Worker Service template. This template is specifically designed for long-running background tasks. Give your project a meaningful name and select your target .NET version (e.g., .NET 8.0).
  2. Install the Windows Services Package: The Worker Service template is cross-platform by default. To make it a Windows Service, you must add a specific library. Right-click your project in the Solution Explorer, select Manage NuGet Packages, and search for Microsoft.Extensions.Hosting.WindowsServices. Install the latest stable version.
  3. Configure Program.cs: Open the Program.cs file. You need to tell the host that it should run as a Windows Service. Find the line where CreateBuilder is called. Add .UseWindowsService() to the builder chain. For example, your code should look like Host.CreateApplicationBuilder(args).UseWindowsService().Build();. This method ensures that the application handles the start and stop signals sent by the Windows Service Control Manager correctly.
  4. Implement the Background Logic: Open the Worker.cs file. This class inherits from BackgroundService and contains the ExecuteAsync method. This is where your actual service logic resides. Inside the while (!stoppingToken.IsCancellationRequested) loop, place the code you want to run periodically. For example, you might use await Task.Delay(1000 * 60, stoppingToken); to make the service run once every minute.
  5. Configure Logging: By default, the Worker Service uses the built-in ILogger. When running as a Windows Service, these logs are typically sent to the Windows Event Viewer. You can verify this by checking the Application logs in the Event Viewer tool. If you need more detailed logs, consider integrating a third-party logging library that writes to a physical file on the disk.
  6. Publish the Application: You cannot simply run the .exe from the bin/Debug folder for a production service. Right-click the project and select Publish. Choose Folder as the target. In the publish settings, it is highly recommended to set the Deployment Mode to Self-contained. This bundles the .NET runtime with your application, meaning the target server does not need the .NET runtime installed separately to run your service.
  7. Create the Windows Service: Once published, copy the files to a permanent directory on the target machine (e.g., C:\Services\MyWorkerService). Open PowerShell or Command Prompt as an Administrator. Use the sc command to create the service. The syntax is: sc.exe create "MyServiceName" binpath= "C:\Services\MyWorkerService\MyWorkerService.exe". Note that there must be a space after binpath=.
  8. Start the Service: After creation, the service is stopped by default. You can start it using the command sc.exe start "MyServiceName" or by opening the Services app (type services.msc in the Start menu), finding your service in the list, right-clicking it, and selecting Start.

Common Mistakes

One of the most frequent errors is failing to run the Command Prompt or PowerShell as an Administrator during the sc create process. Without elevated permissions, Windows will deny access to the Service Control Manager, and the command will fail with an "Access Denied" error.

Another common mistake is neglecting the UseWindowsService() call in Program.cs. If this is omitted, the application will run fine as a console app, but when the Windows Service Control Manager tries to start it, the application will not send the required "Started" signal back to Windows. This results in the service timing out and throwing an error stating that the service did not respond to the start or control request in a timely fashion.

Developers also often forget to use absolute paths in their code. A Windows Service does not run in the same directory as the executable by default; it often starts in C:\Windows\System32. If your code tries to open a file using a relative path like File.ReadAllText("config.json"), the service will crash because it cannot find the file in the System32 folder. Always use AppContext.BaseDirectory to resolve paths relative to the application's installation folder.

Tips

To make your service easier to maintain, set the Start Type to Automatic. This ensures the service starts whenever the machine boots, regardless of whether a user logs in. You can do this via the sc config "MyServiceName" start= auto command or through the Properties menu in services.msc.

For debugging, always keep the application runnable as a console app. Because UseWindowsService() is smart enough to detect if it is running as a service or as a console app, you can debug your logic in Visual Studio using the standard F5 key. Once you are satisfied with the behavior, you can publish it and install it as a service.

Consider using a dedicated service account instead of the LocalSystem account if your service needs to access network shares or specific databases. LocalSystem has high privileges on the local machine but limited privileges on the network, which can lead to "Unauthorized Access" errors when the service tries to reach an external resource.

Troubleshooting

If the service fails to start, the first step is to check the Windows Event Viewer. Go to Windows Logs > Application. Look for errors sourced from your service name or .NET Runtime. This will usually provide the exact exception and stack trace that caused the crash.

If you see an error regarding a missing runtime, ensure you published the app as "Self-contained" or that the correct .NET Runtime version is installed on the host machine. You can check installed runtimes by running dotnet --list-runtimes in the command line.

If the service is stuck in a "Starting" state or refuses to stop, check if your ExecuteAsync method has a blocking call that is ignoring the CancellationToken. If you have a while(true) loop without checking stoppingToken.IsCancellationRequested, the service will ignore the stop command from Windows, forcing you to kill the process via Task Manager.

If the sc create command fails with a syntax error, double-check the space after the equals sign. The command binpath="C:\..." (without a space) is invalid; it must be binpath= "C:\...".

Frequently Asked Questions

Can I use Dependency Injection in a .NET Core Windows Service?

Yes. The Worker Service template is built on the .NET Generic Host, which has built-in support for Dependency Injection. You can register services in Program.cs and inject them into the constructor of your Worker class.

How do I update the code of a running service?

You must stop the service first using sc stop "MyServiceName" or the Services app. Once stopped, replace the files in the installation folder with the new version and start the service again.

Does the service need to be rewritten for different versions of .NET?

Generally, no. The Microsoft.Extensions.Hosting.WindowsServices package is compatible across .NET 6, 7, and 8. You only need to update the NuGet package and the target framework in your project file.

How can I make the service restart automatically if it crashes?

Open services.msc, right-click your service, and go to Properties > Recovery. You can set the "First failure," "Second failure," and "Subsequent failures" options to "Restart the Service."

Can a .NET Core service run on Linux?

The UseWindowsService() method is specific to Windows. However, if you use UseSystemd() from the Microsoft.Extensions.Hosting.Systemd package, you can run the same Worker Service logic as a daemon on Linux using systemd.