考慮到部署方便,我們一般都會將C#寫的Windows服務製作成安裝包。在服務安裝完成以後,第一次還需要手動啟動服務,這樣非常不方便。查閱了網上的一些資料,發現有一種方法是在安裝完成事件裡面調用命令列的方式啟動服務,這種方式雖可行,但覺得不夠完美。好了,下面來看看如何更好地做到服務自動啟動。
1、重寫ProjectInstaller的Commit方法
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、在服務安裝項目中添加名為 Commit的 Custome Action
在服務安裝項目上右擊,在彈出的菜單中選擇View — Custom Actions
然後在Commit項上右擊,選擇Add Custom Action…,在彈出的列表框中選擇Application Folder。最終結果如下:
需要注意的是,第二步操作是必不可少的,否則服務無法自動啟動。我的個人理解是Commit Custom Action 會自動調用ProjectInstaller的Commit方法,Commit Custom Action 在這裡扮演了一個調用者的角色。