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.

static class Program
{
	/// 
	/// The main entry point for the application.
	/// 
	static void Main()
	{
		var service = new MyWindowsService();

		//ServiceBase[] ServicesToRun;
		//ServicesToRun = new ServiceBase[] 
		//{ 
		//    new MyWindowsService() 
		//};
		//ServiceBase.Run(ServicesToRun);
	}
}

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.

public partial class MyWindowsService : ServiceBase
    {
        public MyWindowsService()
        {
            InitializeComponent();
            OnStart(null);
        }

        protected override void OnStart(string[] args)
        {
            //Begin debugging and setting breakpoints.
        }

        protected override void OnStop()
        {
        }
    }

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.