For ease of deployment, we generally make Windows Services written in C # Into an installation package. After the service is installed, You need to manually start the service for the first time, which is inconvenient. I checked some information on the Internet and found that one method is to call the command line method to start the service in the installation completion event. This method is feasible but not perfect. Now let's take a look at how to better enable the service automatically.
1. Override the Commit method of ProjectInstaller
Using System;
Using System. Collections;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Configuration. Install;
Using System. Linq;
Using System. ServiceProcess;
Namespace CleanExpiredSessionSeivice
{
[RunInstaller (true)]
Public partial class ProjectInstaller: System. Configuration. Install. Installer
{
Public ProjectInstaller ()
{
InitializeComponent ();
}
Public override void Commit (IDictionary savedState)
{
Base. Commit (savedState );
// Auot start service after the installation is completed
ServiceController SC = new ServiceController ("CleanExpiredSessionSeivice ");
If (SC. Status. Equals (ServiceControllerStatus. Stopped ))
{
SC. Start ();
}
}
}
}
2. Add the Custome Action named Commit to the service installation project.
Right-click the service installation project and choose View-Custom Actions from the shortcut menu.
Www.2cto.com
Right-click the Commit item and choose Add M Action ..., Select Application Folder in the pop-up list box. The final result is as follows:
Note that the second step is essential, otherwise the service cannot be started automatically. My personal understanding is that Commit Custom Action will automatically call the Commit method of ProjectInstaller. Commit Custom Action plays a caller role here.
Author: Chen Feng