How To Debug Windows Service OnStart
The article, How to: Debug Windows Service Applications details how to attach to a running process to debug a service. This works when the code you're debugging a logical issue rather than finding the root cause of an early failure when the service starts up. Debugging the OnStart method can be problematic. According to the article:
One way to work around this is to create a temporary second service in your service application that exists only to aid in debugging. You can install both services, and then start this "dummy" service to load the service process. Once the temporary service has started the process, you can then use the Debug menu in Visual Studio to attach to the service process.
After attaching to the process, you can set breakpoints and use these to debug your code. Once you exit the dialog box you use to attach to the process, you are effectively in debug mode. You can use the Services Control Manager to start, stop, pause and continue your service, thus hitting the breakpoints you've set. You would later remove this dummy service after debugging is successful.
Rather than creating a new service solely for debugging purposes, you can use the System.Diagnostics.Debugger.Launch method. In order to use this approach the service must be compiled for Debug and the PDB file must be available and preferably in the same directory as the installed service. Don't forget that you don't need a MSI to install the service. Running installutil.exe against a DLL containing an Installer for the service is sufficient.
After you install and start the service, on Vista, you are presented with the following dialog:
After selecting, "Yes, debug MyNewService.exe" you will be presented with a dialog asking whether or not you want to grant or deny access. Accessing services requires administrator level access. Then, you're given the option to load the IDE:
Finally, the Visual Studio .NET IDE will load and with the breakpoint set to the line with Debugger.Launch.
Just make sure to remove this line of code before you check the service back into a source control system. This is something that should never go into a production environment.
While writing this entry I also came across a useful post documenting five different ways to debug a Windows service: