A service project created in Visual Studio cannot be directly started in the debugger. A small tweak enables direct running of the service and gets rid of the need to deploy the service to test it.

From the first time I tried developing a Windows Service in C++ back in the good old days before .NET I’ve always found them awkward to debug. When developing I want to have my environment setup with multiple startup projects so that I can open a solution, hit F5 and have everything required running. If the solution contains a service a tedious compile-install-start service-attach debugger procedure is required.

Last week when I created a service I decided to find a better way, a way that enables the simple “press F5 to get everything running” approach. Since a service project already compiles to an .exe file, it can be changed to check if it is run as a service or interactively during startup. If running interactively, a reflection hack is used to call each service’s OnStart method.

The first step is to change the service application to be a console app instead of a windows app. I you prefer to use WinForms or WPF for the interactive GUI you should leave it as it is, but that would make a background service dependent on UI libraries which I don’t like. Besides, the GUI is not the essential part of this app. It’s target at developers so a console app will do.

First the Main function has to be modified to check if it is run interactively or as a service.

A check is done for Environment.UserInteractive to choose between interactive mode and normal service mode. This might cause problems with services running in interactive mode. (I haven’t tested and don’t intend to – because a service running interactively is often a security problem. If you have to communicate with the user, build a small client app that is auto started instead.)

The real work is done in the RunInteractive helper method. It calls the OnStart method of each service. Then it waits for a keypress before calling OnStop of each service. The OnStart and OnStop methods are protected and not intended to be called from the outside. Since this is a debug aid I think it is okay to use reflection to call the nonpublic methods.

With the service library set up this way it can be set to start together with other projects automatically when starting a debug session in Visual Studio. Enabling everything to start with one button (F5) really speeds up the coding and debugging.