Introduction
Normally, debugging a Windows service under Visual Studio .NET is painful. Windows services won't actually run directly within Visual Studio .NET, so the usual technique is to install and start the Windows service and then attach a debugger to it. An alternative approach is to pull the guts out of the service, stick it in a separate library, and then build some other app (e.g., a console app) to sit in front of it. This approach uses neither of those techniques.
When building a C# Windows Service project in Visual Studio, it will leave you with a class containing quite a few methods including a Main()
, such as this:
static void Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
Obviously, it's the Main()
above that ends up executing the service, and it's the Main()
that this approach manipulates so that the Windows Service can be debugged directly within Visual Studio .NET.
Using the example above (and removing some of the comments), here's how:
static void Main()
{
#if (!DEBUG)
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
#else
Service1 service = new Service1();
service.<Your Service's Primary Method Here>();
// Put a breakpoint on the following line to always catch
// your service when it has finished its work
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#endif
}
It's crude, but effective (CBE - also known as Commander of the British Empire ;)). Run the service in debug mode to debug it, compile and install it as a release build, and it's a full and proper Windows service.
You may still wish to pull the guts out of your service into a separate library for unit testing. But this approach allows you to work with almost all of your service code as an actual service.