Whem I'm writing a Windows Service and just hit F5 I get the error message that I have to install it using installutil.exe
and then run it.
In practice this means everytime I change a line of code:
- compile
- switch to Developer Command Prompt
- remove old version
- install new version
- start service
That is very inconvenient. Is there a better way to do it?
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.
You cannot run Windows Service as say another console or WinForms application. It needs to be started by Windows itself.
If you don't have infrastructure ready to use as @Damien_The_Unbeliever suggests (which is what I recommend as well) you can install the service from the debug location. So you use installutil
once and point it to executable located in /bin/debug
. Then you start a service from services.msc
and use Visual Studio > Debug > Attach to Process
menu and attach to the Windows service.
You can also consider using Thread.Sleep(10000)
as the first line in the OnStart
call, or Debugger.Break()
to help you out to be able to attach before the service executes any work. Don't forget to remove those before the release.
You can use Environment.UserInteractive
variable. Details of implementation here
来源:https://stackoverflow.com/questions/16604822/running-windows-service-application-without-installing-it