My C# Windows Service Adventure in .NET 7

4 min readJul 7, 2023
Photo by Erik Mclean on Unsplash

Services have been around for a very long time. They should be easy. They ought to be easy. I found out very quickly there are some major caveats, or sticking points, that make services in the .NET 7 and Windows Server difficult and frustrating to use.

Come along with me on my journey to creating C# Windows service. Maybe this will help you on your journey.

The Quest

We are currently in the process of modernizing our distribution system. The system, which is around 20 years old, is finally starting to become frail and prone to outages. The system is comprised of around a thousand individual applications. While the frontend work is going well, the backend service that do most of the heavy lifting are poorly written and slow.

Thus, we don’t just need to rewrite these backend services but also improve their performance, visibility, and maintainability. The system uses files and timed schedules to function. When the scheduling system fails or files aren’t generated the whole system comes to a stand still.

We’ve decided to move to a messaging system, Kafka, to enable real and immediate responsiveness in the new version of the ecosystem. However, I failed to convince the team to move to containerized application developer and using tools like Docker Swarm or Kubernetes to allow these applications to always run.

We’re left with only one option, using Windows Server and Windows services.

The Plan

In my initial research it seems fairly easy to get start with Windows services. Doing a quick google search lead me to a quick start guide provided by Microsoft.

Using a Background Service and a generic host we can create something that continually runs and listening for new messages from our messaging system.

Then, we can create a Windows service by using the following NuGet

<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="7.0.1" />

Next, we add the services required to run as a service to our generic host, as show in the referenced…