How to debug a windows service without installing ?

How to debug a windows service without installing ?

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.

Shashank Bisen

Shashank Bisen is curious blogger and speaker who love to share his knowledge and experience which can help anyone in their day to day work. 

2 Comments to “How to debug a windows service without installing ?”

Comments are closed.