For a long while I’ve been debugging a .NET service using the recommended approach. Whilst this works, it’s kind of painful. the steps are something like this
- Build the service
- Realise the service was already running. Stop it from the Services Control Panel applet.
- Build the service again
- Start the service from the Services Control Panel applet.
- Attach to the process from Visual Studio
- Realise the service has already executed the piece of code I wanted to debug.
- Goto step 1.
There had to be a better way. And a bit of Googling brought up this approach. But I didn’t really understand how it worked. I guess I’d assumed the error shown in Visual Studio when you try to debug a service was actually coming from Visual Studio, but I now realise the error is coming from .NET. So by having a different piece of code run when in debug mode, the service is treated like any old application.
My solution is slightly different so I can also test the service starting and stopping. My service implementation has StartService and StopService public methods, which are called from OnStart and OnStop. And my Main method looks like this.
static void Main() { #if (!DEBUG) ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new MyService() }; ServiceBase.Run(ServicesToRun); #else WorkflowService service = new MyService(); service.StartService(); service.DoStuff(); service.StopService(); #endif }
No comments:
Post a Comment