C# – How to debug the .NET Windows Service OnStart method

cdebuggingnet

I have code written in .NET that only fails when installed as a Windows service. The failure doesn't allow the service to even start. I can't figure out how I can step into the OnStart method.

How to: Debug Windows Service Applications gives a tantalizing clue:

Attaching to the service's process allows you to debug most but not all of the service's code; for example, because the service has already been started, you cannot debug the code in the service's OnStart method this way, or the code in the Main method that is used to load the service. 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.

However, I'm not clear how it is exactly that you are supposed to create the dummy service to load the service process.

Best Answer

One thing you could do as a temporary workaround is to launch the debugger as the first line of code in the OnStart

System.Diagnostics.Debugger.Launch()

This will prompt you for the debugger you'd like to use. Simply have the solution already open in Visual Studio and choose that instance from the list.