天天看點

.Net實作Windows服務安裝完成後自動啟動的兩種方法

考慮到部署友善,我們一般都會将C#寫的Windows服務制作成安裝包。在服務安裝完成以後,第一次還需要手動啟動服務,這樣非常不友善。

此操作之前要先設定下兩個控件

設定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");  

    }  

查閱了網上的一些資料,這種方式雖可行,但覺得不夠完美。好了,下面來看看如何更好地做到服務自動啟動。

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

.Net實作Windows服務安裝完成後自動啟動的兩種方法

然後在Commit項上右擊,選擇Add Custom Action…,在彈出的清單框中選擇Application Folder。最終結果如下:

.Net實作Windows服務安裝完成後自動啟動的兩種方法

需要注意的是,第二步操作是必不可少的,否則服務無法自動啟動。我的個人了解是Commit Custom Action 會自動調用ProjectInstaller的Commit方法,Commit Custom Action 在這裡扮演了一個調用者的角色。

繼續閱讀