考慮到部署方便,我們一般都會將C#寫的Windows服務制作成安裝包。在服務安裝完成以后,第一次還需要手動啟動服務,這樣非常不方便。
方法一:在安裝完成事件里面調用命令行的方式啟動服務
此操作之前要先設置下兩個控件
設置serviceProcessInstaller1控件的Account屬性為“LocalSystem”
設置serviceInstaller1控件的StartType屬性為"Automatic"
設置serviceProcessInstaller1控件的Account屬性為“LocalSystem”
設置serviceInstaller1控件的StartType屬性為"Automatic"
在服務器上添加安裝程序,在private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)事件中,添加以下代碼:
- /// <summary>
- /// 安裝后自動啟動服務
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
- {
- Process p = new Process
- {
- StartInfo =
- {
- FileName = "cmd.exe",
- UseShellExecute = false,
- RedirectStandardInput = true,
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- CreateNoWindow = true
- }
- };
- p.Start();
- const string cmdString = "sc start 銀醫通服務平台1.0"; //cmd命令,銀醫通服務平台1.0為服務的名稱
- p.StandardInput.WriteLine(cmdString);
- p.StandardInput.WriteLine("exit");
- }
查閱了網上的一些資料,這種方式雖可行,但覺得不夠完美。好了,下面來看看如何更好地做到服務自動啟動。
方法二:使用ServiceController對象
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);
- ServiceController sc = new ServiceController("銀醫通服務平台1.0");
- 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 在這里扮演了一個調用者的角色。