Here’s a quick tip for running a C#.NET or VB.NET Windows Service in debug mode inside Visual Studio.
First – modify the Main() in your C# or VB project to start as an instance instead of as a service.
C#
static void Main()
{
#if DEBUG
var service = new MyService();
service.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(ServicesToRun);
#endif
}
VB.NET
Shared Sub Main()
#If DEBUG Then
Dim service As MyService = New MyService
service.OnDebug()
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite)
#Else
Dim ServicesToRun() As System.ServiceProcess.ServiceBase
ServicesToRun = New System.ServiceProcess.ServiceBase() { New MyService }
System.ServiceProcess.ServiceBase.Run(ServicesToRun)
#End If
End Sub
Now modify the Main Service code of your Service to add an OnDebug() event. The easiest way to do this is to inject the code before the OnStart() service.
C#
#if DEBUG
public void OnDebug()
{
Debugger.Launch();
OnStart(null);
}
#endif
VB.NET
#If DEBUG Then
Protected Sub OnDebug()
Debugger.Launch()
OnStart(Nothing)
End Sub
#End If
If you make the above amendments you will be able to run your Windows Service in Visual Studio in debug mode. You’ll need the Build Configuration set to DEBUG because of the build environment variable flag. The OnStart condition in both languages above defines a null ARGS parameter. If your Service depends on Args on the start up, you should specify the default set of arguments you want to use during testing.