Debugging Windows Services Inside Visual Studio

Windows Services are computer programs that operate in the background, sort of like a daemon on Linux-based operating systems. Since these programs run inside a managed container, it must adhere to a specific protocol and inherit from ServiceBase. In this article, I’ll cover the common scenario most .NET developers run into: the desire to debug their service without having to deploy it to the managed service container every time they make a change.

There are just a couple of hacks you need to make to the start up code to make it runnable.

The first thing is to comment out the default generated code that invokes the Windows Service in the Program.cs file and directly instantiate your class that inherits from ServiceBase as shown below.

Next, modify the constructor to call the OnStart() method of your service class. This change is necessary because OnStart is only accessible to child classes.

Now you can run the debugger, bypassing the service container invocation. It’s a quick and easy hack that saves time when you don’t want to keep redeploying your code.