views:

200

answers:

3

How to run a windows service project from visual studio.

I am building a windows serivce in visual studio 2008, I have to always run the service from control panel and then attach the debugger to running instance of the service. Its kind of annoying since I am cleaning a lot of code and need to restart my service many times during development.

I want to setup my project so as to be able to hit F5 and run the service and directly enter the debug mode. Some tips on how to achieve this would be great.

Thanks in advance!!!

+3  A: 

In your Main() routine check for Debugger.IsAttached and if it's true start your app as if it's a console, if not, call into ServiceBase.Run().

Sam
+2  A: 

Create a seperate project that just references the service project and instantiate and start the service. It just runs like a normal app and you can step into it.

YourService s = new YourService();
s.Start();
sadboy
A: 

Copied from here.

static void Main(string[] args)  
{  
    DemoService service = new DemoService();  

    if (Environment.UserInteractive)  
    {  
        service.OnStart(args);  
        Console.WriteLine("Press any key to stop program");  
        Console.Read();  
        service.OnStop();  
    }  
    else 
    {  
        ServiceBase.Run(service);  
    }  
}  

This should allow you to run from within Visual Studio.

Another way would be to embed a programmatic breakpoint in your code by calling System.Diagnostics.Debugger.Break(). When you place this in, say, the OnStart() callback of your service and start your service from the Services console, the programmatic breakpoint will trigger a dialog box that allows you to attach to an existing instance of Visual Studio or to start a new instance. This is actually the mechanism I use to debug my service.

Matt Davis