Friday, March 12, 2010

Code: How To Run a .Net Windows Service as a Console Application

Attempting to debug a windows service can be a nightmare, especially if you are trying to debug the OnStart event by attaching to a local process.  To get around this you can configure the windows service to launch as a console application.  To do this go to the property pages of your service and select the Application tab.  Change the output type to Console Application:

image

Next modify the program.cs file by adding an args input parameter to the Main method and surrounding the logic in the method with an if statement like so:

Code Snippet
  1. static void Main(string[] args)
  2. {
  3.     if (args.Length == 0)
  4.     {
  5.         ServiceBase[] ServicesToRun;
  6.         ServicesToRun = new ServiceBase[]
  7.         {
  8.         new Service1()
  9.         };
  10.         ServiceBase.Run(ServicesToRun);
  11.     }
  12.     else
  13.     {
  14.         //DoWork();
  15.     }
  16. }

Now modify your service1.cs file to call the same worker method on start:

Code Snippet
  1. public partial class Service1 : ServiceBase
  2. {
  3.     public Service1()
  4.     {
  5.         InitializeComponent();
  6.     }
  7.  
  8.     protected override void OnStart(string[] args)
  9.     {
  10.         //DoWork();
  11.     }
  12.  
  13.     protected override void OnStop()
  14.     {
  15.     }
  16. }

Finally go to the Debug tab on the property pages and add a word to the Command line arguments text box:

image

Now just start debugging and your breakpoint will be hit!

image