How to debug Windows Service Without installing it

While developing a Windows service if you want to debug or run it will give you the following message.

"Cannot start service from the command line or a debugger.A Windows Service must first be installed (using installutil.exe) and then started with the ServerExplorer, Windows Services Administrative tool or the NET START command."

So for debugging you first install the service, but it is a long process because every time you make changes, you need to reinstall your service and debug it again.

Here is the solution for avoiding this long process.

For debugging your service without installing it, make changes in Program.cs like this.
Suppose if your Program.cs file is

static class Program
{
    static void Main()
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
{
    new MyWindowsService()
};
        ServiceBase.Run(ServicesToRun);
    }
}

Change the above code like below

static class Program
{
    static void Main()
    {
        #if(!DEBUG)
           ServiceBase[] ServicesToRun;
           ServicesToRun = new ServiceBase[]
  {
       new MyWindowsService()
  };
           ServiceBase.Run(ServicesToRun);
         #else
           MyWindowsService myWindowsServ = new MyWindowsService();
           myWindowsServ.RunService();
         
         #endif
    }
}

Here RunService is My Service function that initiates the OnStart Event of the Service.

Now if you run your service then it will not show you the above message. It simply runs the service. Now you can debug you application by simply adding the breakpoints.


Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment