Running .NET Windows service project from debugger

It sounds like an easy task, but I have seen many times that people actually do some strange stuff, trying to run a .NET project containing Windows service from debugger. So decided I'll write a small note on how do I do that.

If you create a project for Windows service, using wizard in Visual Studio, try to execute it straight from debugger. You'll get that service cannot start or something similar. I do a small trick by checking if debugger is attached and calling some sort of Start method in such case, or executing code created by wizard otherwise. See example below :

   1: [DllImport("Kernel32.dll")]
   2: private static extern bool AllocConsole();
   3:  
   4: static void Main()
   5: {
   6:     MyService service = new MyService();
   7:  
   8:     if (!System.Diagnostics.Debugger.IsAttached)
   9:     {
  10:         ServiceBase.Run(service);
  11:     }
  12:     else
  13:     {
  14:         //open console
  15:         AllocConsole();
  16:  
  17:         service.Start();
  18:         Console.WriteLine("Press ENTER to exit...");
  19:         Console.ReadLine();
  20:         service.Stop();
  21:     }
  22: }

There is a small addition I usually do - open a console window (you can get the similar effect by setting project's output type to Console Application, but I just prefer it this way). The Win32 API method AllocConsole will create a console window if it doesn't exist yet, so you can actually write to and read from it as usual.

Cheers.

Technorati Tags: ,

posted @ Tuesday, September 18, 2007 6:43 PM

Print

Comments on this entry:

No comments posted yet.

Your comment:



 (will not be displayed)


 
 
 
Please add 3 and 5 and type the answer here:
 

Live Comment Preview: