How to debug a windows service without installing ?

By | July 2, 2015

It is not easy to debug a windows service with the help of Visual Studio. We won’t be able to run them directly from Visual Studio, we need to install and start the service and further attach a debugger to it. So let’s see how we can make sure we can debug a windows service without installing it with ease.

In the Main method of your program file, let’s make few changes.

 

private static void Main()
{
ServiceBase[] servicesToRun = new ServiceBase[]
{
new Service()
};

if (Environment.UserInteractive)
{
RunInteractive(servicesToRun);
}
else
{
ServiceBase.Run(servicesToRun);
}
}

Must Read : 10 Effective Debugging Tips for .NET Developer

private static void RunInteractive(ServiceBase[] servicesToRun)
{
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("{0} Started", service.ServiceName);
}

Console.WriteLine("Press any key to stop the service {0}", service.ServiceName);
Console.Read();
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("{0} Stopped", service.ServiceName);
}
Thread.Sleep(1000);

Here we check if the Environment is UserInteractive then we call the OnStart method of each service and wait for a keypress before calling OnStop. As these method are protected we need to use reflection to call them. Now you are free to use (F5) for debugging.

2 thoughts on “How to debug a windows service without installing ?

  1. Pingback: Generic Constraints - The Daily Six Pack: July 3, 2015

  2. Pingback: Visual Studio – Developer Top Ten for July 6th, 2015 - Dmitry Lyalin

Comments are closed.