Debugging .NET Services

Not Web Services, but Windows Services...

First of all, writing a windows service is pretty easy (just start with the Windows Service project template) but testing it can be tough. It's better to write your logic in a separate assembly (and write NUnit tests to verify the functionality) and then add the Windows Service as a facade to that assembly.

Sometimes, though, you really wanna just break into the debugger while the service is running, right?

It turns out its not that hard to do:

  1. Add the service account that is used by the service to your local Debugger Users group (Computer Management/Local Users and Groups). Usually the service account is "Network Service" or "Local Service" or a specific account you have chosen to use.
  2. In your source code, add the following line of code wherever you want to break into debug mode:
    System.Diagnostics.Debugger.Break()
  3. Compile your service and install it (I'm gonna blog about installers and InstallUtil later).
  4. Start your service from a command line (Net Start MyService).

When the service hits the line of code inserted in Step 2 above, it will ask you if you want to debug the application, using a CLR debugger, the current instance of Visual Studio (this is what you want), or a new instance of Visual Studio. If you didn't get the right account in Debugger Users in step 1, you will get an "Access Denied" message instead of the question about debugging.

From this point, you will be able to step through your code and do your normal debugging.

Don't forget to remove the line of code that breaks into the debugger before completing your project! It's probably a better practice to use a compiler directive to ensure that you don't compile in the Debugger.Break() call into your release code.

In order to recompile your application (since you're debugging it, you're probably expecting to find some bugs, right?), you will have to stop the service and uninstall it again before re-compiling. I usually have two batch files that will help me do that: one to install and start the service, another to stop the service and uninstall it.

Happy debugging!

 

1 Comment

Comments have been disabled for this content.