Just a quick post with a tip for those of you who are working on windows services. You’ll probably come across the same problem I did some time ago when I first tried it – you can’t just click debug and step through a windows service, it has to be installed and run as a service outside the debugger.
A lot of sites and articles will tell you to use eventlogs and traces then as step debugging is impossible, or to try and manually hook into the process using “attach debugger to process”. The first is just plain wrong, and the second a pain in the ass. There is an easier way.
The answer lies in the System.Diagnostics.Debugger class, specifically it’s static launch method. Just add this to the start of your OnStart event:
and stick a breakpoint after it in your code. Keep the ide open when you start the service and it will ask you to choose a debugger – giving the open ide as an option. Choose it and it will launch straight into a step by step of your source code. Easy.
Of course, having that line in there is a pain when you want to release the service, so add a #if conditional to check the code. This ensures that the debugger launch command is included when the system is compiled in a debug configuration, and not when configured in release configuration. The updated code is as follows:
This code will not even be included in the assembly when compiled outside of debug mode.
Two simple concepts of boundless value. Enjoy. 🙂