Running a Service as an Application
| October 20, 2011 | in
Windows services are really cool, but they can be a little bit of a pain to work with. To debug a windows service, the typical model requires you to attach to the services process. This is incredibly annoying after you do it for the 10th time, but the good news is there’s an easy alternative.
Windows services are simply executables, but they won’t directly run. If you click on one or try running it from the command line you’ll get an error. However, in Visual Studio 2010 you can easily change that behavior so you provide a command line argument when running the .exe, it will run the service like a console application.
First, we right-click on the service project and select Properties. On the Properties page, click the Application tab and change the Output type to “Console Application”.
Next, we’ll add a command line parameter for a debug application. Click the Debug tab and enter “console” in the Command line arguments box.
Then we need to update the service implementation by adding two methods, StartService and StopService. Both of these should be called by OnStart and OnStop respectively.
Lastly, we update the program.cs file to check for the presence of a command line argument. If the command line argument exists, then it will run the service in Console mode. If the argument doesn’t exist, then it will run as a normal service. The code below doesn’t explicitly check for the word “console” entered in step two. You could add such a check if you want, but it isn’t necessary.
If you set the service project as the default project, you should be able to run it by just pressing F5.