Friday, June 17, 2016

Install Window Service Programmitcally

You can do it all in one executable. To pass installation parameters, you will need to derive classes System.ServiceProcess.ServiceProcessInstaller and System.ServiceProcess.ServiceInstaller. You only need to implement constructors of your classes.

Installation and uninstallation will be done by System.Configuration.Install.AssemblyInstaller. This class should use the assembly where the classes based on ServiceProcessInstaller and ServiceInstaller are implemented; the implementation will be found in your assembly automatically (which would create a hard-to-detect failure if you have a bug in the implementation). Not too bad though.

Finally, start/stop, etc. are handled by your service code which you create deriving the class System.ServiceProcess.ServiceBase. Triggering this actions is done by Service Controller. To do it programmatically you should use the class System.ServiceProcess.ServiceController.

You need to have a good reading of MSDN on the topics around the classes I listed above, which is well illustrated by code samples. This information is easy to find, a bit harder to understand the work flow and what happens in which process. (A Windows Service process is always a separate one; it takes another process to run installation and Service Controller part.) You can use all this like a cookbook, but I suggest you thoroughly understand it; in this case you won't have any problems.

You can even try to implement it all in one application as I did, but you still need to run it in at least two different processes: one would work in the Windows Service mode, another is must be interactive mode, which can be anything else, such as UI, Console or just invisible batch-mode application.

Important! You code can test System.Environment.UserInteractive during run time to calculate is currently running code is run as Windows Service or not.

No comments:

Post a Comment