Running Windows Service Application without installing it

You can write this code in program.cs

//if not in Debug
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] 
{ 
   new MyService() 
};
ServiceBase.Run(ServicesToRun);

//if debug mode
MyService service = new MyService();
service.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);

in MyService class

public void OnDebug()
{
   OnStart(null);
}



I usually put the bulk of the service implementation into a class library, and then create two "front-ends" for running it - one a service project, the other a console or windows forms application. I use the console/forms application for debugging.

However, you should be aware of the differences in the environment between the debug experience and when running as a genuine service - e.g. you can accidentally end up dependent on running in a session with an interactive user, or (for winforms) where a message pump is running.


The best way in my opinion is to use Debug directive. Below is an example for the same.

#if(!DEBUG)
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[] 
    { 
         // Calling MyService Constructor 
            new MyService() 
    };
     ServiceBase.Run(ServicesToRun);
#else
  MyService serviceCall = new MyService();
  serviceCall.YourMethodContainingLogic();
#endif

Hit F5 And set a Breakpoint on your YourMethodContainingLogic Method to debug it.