Debugging Windows Service StartUp
Lately I have been trying to find a good and simple way to debug a Windows Service Project most ways I came a cross on the web have suggested Starting your widows service with a sleep timer which will allow enough time to attache a debugger to to your service. The other common way of doing this is to initiate a debugger launch each time the service Startup and to control the debugger launching in a configurable manageable way. I found this to approaches rather complicated.
In this post I will suggest an alternate method of debugging a service at startup.
Step 1: Create a windows service project :
Step 2: Create two new services, one will be your main service which will perform all of your service logic, the other one will be you debug service. The debug service will help us debug the main service OnStart. This will looks a little something like this:
Please note that in order to identify both Services in Services window we need to specify their names:
Debug service:
29 private void InitializeComponent()
30 {
31 //
32 // Service2
33 //
34 this.ServiceName = "DebugService";
35
36 }
Main service:
29 private void InitializeComponent()
30 {
31 //
32 // Service1
33 //
34 this.ServiceName = "MainService";
35
36 }
Step 3: Add an Installer to your solution and place both of your services in the designer:
Make sure you have named your services in the installer, I prefer naming them with the same prefix this way both of the services will be displayed together in the services list.
34 // ServiceName must equal those on ServiceBase derived classes.
35 serviceInstaller1.ServiceName = "MainService";
36 serviceInstaller2.ServiceName = "MainDebugService";
Step 4: In you program.cs make sure that both services are added to the ServicesToRun:
16 ServiceBase[] ServicesToRun;
17 ServicesToRun = new ServiceBase[]
18 {
19 new MainService(),new DebugService()
20 };
21 ServiceBase.Run(ServicesToRun);
Step 5: Install your service, in the command prompt type "installutil.exe <YourService.exe>". You can view the services list and check that you services are added successfully.
Now all you have to do if you wish to debug your OnStart method is to Start your DebugService, then attach a debugger to the process.exe, place a break point at the OnStart and finally start your MainService.
*Njoy