.Net Windows服務安裝完成後自動啟動

來源:互聯網
上載者:User

考慮到部署方便,我們一般都會將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 在這裡扮演了一個調用者的角色。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.