Visual-studio – how to run(F5) windows service from visual studio

debuggingtestingunit testingvisual studiowindows-services

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!!!

Best Answer

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.