前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >.Net Windows服务安装完成后自动启动

.Net Windows服务安装完成后自动启动

作者头像
跟着阿笨一起玩NET
发布2018-09-18 13:19:30
1.4K0
发布2018-09-18 13:19:30
举报

考虑到部署方便,我们一般都会将C#写的Windows服务制作成安装包。在服务安装完成以后,第一次还需要手动启动服务,这样非常不方便。查阅了网上的一些资料,发现有一种方法是在安装完成事件里面调用命令行的方式启动服务,这种方式虽可行,但觉得不够完美。好了,下面来看看如何更好地做到服务自动启动。

    1、重写ProjectInstaller的Commit方法

代码语言:javascript
复制
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();
            }
        }
    }
}

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

    2、在服务安装项目中添加名为 Commit的 Custome Action

     在服务安装项目上右击,在弹出的菜单中选择View — Custom Actions

image
image

然后在Commit项上右击,选择Add Custom Action…,在弹出的列表框中选择Application Folder。最终结果如下:

image
image

需要注意的是,第二步操作是必不可少的,否则服务无法自动启动。我的个人理解是Commit Custom Action 会自动调用ProjectInstaller的Commit方法,Commit Custom Action 在这里扮演了一个调用者的角色。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2011-12-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档