Running Windows Services in Visual Studio

Have you ever wanted to run a Windows service, without installing it, through Visual Studio? It’s actually not that hard to do this.

This is useful in cases where you have a component which is a Windows service, and you need to run integration tests against that service, but don’t want the hassle of continuously installing and uninstalling the service; you just want to use the latest code version.

The safest way to do this (although I wouldn’t recommend checking this in to your production code-line) would be to check if the environment is interactive (or if the debugger is running), and simply invoke the service directly, then keep the process suspended.

static void main() {
ServiceBase someService = new ServiceBase[] { new MyService() };
if (!Environment.UserInteractive) {
} else {
someService[0].OnStart(new string[0]); // Pass no command-line args
while (true) {
Thread.Sleep(100); // Suspended animation

Yep, that’s right, I used an infinite loop and didn’t call OnStop. Like I said, this is a quick and dirty solution to get around this problem.

As an alternative, you can use InstallUtil, PowerShell, or some other methods — which I’m not familiar with and can’t recommend.

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Core .NET, Wndows Forms and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *