Debugging a .NET Windows service within the IDE

The Visual Studio documentation insists that you must install your Windows service before you can run it and debug it. During development of a service, it can be a real pain to have to uninstall the previous version and then re-install a new version every time you want to test a change to your code. Fortunately, you can set-up your service so that when using the Debug configuration it operates as a standard executable, and when using the Release configuration it reverts back to being a normal Windows service. This allows you to debug your service from within the Visual Studio IDE, without any messy installing and un-installing.

To do this, you need to emulate what the Service Control Manager (SCM) does when it starts your service — in other words, invoke your service’s OnStart method. In C#, this looks like:

And in VB, this looks like:

This approach also allows you to debug your Main procedure and the code in your OnStart method. This is otherwise rather tricky because these two procedures have already been executed (during service startup) before you get a chance to attach to the service process for debugging. This debugging trick has the additional benefit that if you want to debug other service commands such as Stop or Pause, you can just invoke the appropriate method directly from the IDE's Immediate window.

UPDATED: Len Holgate has a more sophisticated version of this idea, where he completely decouples the service from the SCM.