Debugging a Windows Service Project

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.

static void Main()
{
    ServiceBase[] servicesToRun;
    servicesToRun = new ServiceBase[] 
    {
        new MyService()
    };
    if (Environment.UserInteractive)
    {
        RunInteractive(servicesToRun);
    }
    else
    {
        ServiceBase.Run(servicesToRun);
    }
}

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.

static void RunInteractive(ServiceBase[] servicesToRun)
{
    Console.WriteLine("Services running in interactive mode.");
    Console.WriteLine();
 
    MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart", 
        BindingFlags.Instance | BindingFlags.NonPublic);
    foreach (ServiceBase service in servicesToRun)
    {
        Console.Write("Starting {0}...", service.ServiceName);
        onStartMethod.Invoke(service, new object[] { new string[] { } });
        Console.Write("Started");
    }
 
    Console.WriteLine();
    Console.WriteLine();
    Console.WriteLine(
        "Press any key to stop the services and end the process...");
    Console.ReadKey();
    Console.WriteLine();
 
    MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop", 
        BindingFlags.Instance | BindingFlags.NonPublic);
    foreach (ServiceBase service in servicesToRun)
    {
        Console.Write("Stopping {0}...", service.ServiceName);
        onStopMethod.Invoke(service, null);
        Console.WriteLine("Stopped");
    }
 
    Console.WriteLine("All services stopped.");
    // Keep the console alive for a second to allow the user to see the message.
    Thread.Sleep(1000);
}

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.

6 comments

    1. Perfect! Services are often very useful, but I avoided like the plague because debugging, and thus development, sucked. This is for sure saved in my templates folder!

  1. Loved the code. Still crashing and finding my issue.

    Works as an Application fine, but when running as a service it crashes.

    Thanks!

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.