Quando andiamo in deploy con un servizio C# abbiamo l’opzione di utilizzare installutil.exe per “installare” il servizio, ovvero far si che compaia nel Service Control Manager. Tuttavia è possibile fare la stessa cosa programmaticamente, e farlo semplifica la vita a chi installera il vostro servizio. L’idea è che il main del servizio risponda a dei comandi sulla cmd line, per esempio “—install” o “—uninstall” in modo che l’unico strumento che serve in fase di deploy sia il servizio stesso.
Ecco dunque la ricetta: si deve intendere “ricetta” come un segmento di codice troppo piccolo da essere messo in una libreria, ma troppo importante per essere dimenticato 
La ricetta in oggetto è quindi composta di due funzioni:
Install()
1: private static void Install()
2: { 3: ServiceProcessInstaller ProcesServiceInstaller = new ServiceProcessInstaller();
4: ProcesServiceInstaller.Account = ServiceAccount.LocalSystem;
5:
6: ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
7: InstallContext Context = new System.Configuration.Install.InstallContext();
8: String path = String.Format("/assemblypath={0}", Assembly.GetExecutingAssembly().Location); 9: String[] cmdline = { path }; 10:
11: Context = new System.Configuration.Install.InstallContext("", cmdline); 12: ServiceInstallerObj.Context = Context;
13: ServiceInstallerObj.DisplayName = "Nome da visualizzare in SCM";
14: ServiceInstallerObj.Description = "Descrizione del servizio";
15: ServiceInstallerObj.ServiceName = "NomeDelServizio";
16: ServiceInstallerObj.StartType = ServiceStartMode.Automatic;
17: ServiceInstallerObj.Parent = ProcesServiceInstaller;
18:
19: System.Collections.Specialized.ListDictionary state = new System.Collections.Specialized.ListDictionary();
20:
21: ServiceInstallerObj.Install(state);
22: }
Uninstall()
1: private static void Uninstall()
2: { 3: ServiceProcessInstaller ProcesServiceInstaller = new ServiceProcessInstaller();
4: ProcesServiceInstaller.Account = ServiceAccount.LocalSystem;
5:
6: ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
7: InstallContext Context = new System.Configuration.Install.InstallContext();
8: String path = String.Format("/assemblypath={0}", Assembly.GetExecutingAssembly().Location); 9: String[] cmdline = { path }; 10:
11: Context = new System.Configuration.Install.InstallContext("", cmdline); 12: ServiceInstallerObj.Context = Context;
13: ServiceInstallerObj.ServiceName = "ServiceName";
14: ServiceInstallerObj.Uninstall(null);
15:
16: }
Importante: Per entrambe le funzioni, ServiceName deve essere uguale alla proprietà ServiceName del servizio che si vuole installare.