安装后如何自动启动服务?

Jas*_*n Z 52 .net service installer

从Visual Studio安装项目运行安装后如何自动启动服务?

我只想出这个,并认为我会分享一般的好处的答案.回答如下.我对其他更好的方法持开放态度.

Jas*_*n Z 56

将以下类添加到项目中.

using System.ServiceProcess;  

class ServInstaller : ServiceInstaller
{
    protected override void OnCommitted(System.Collections.IDictionary savedState)
    {
        ServiceController sc = new ServiceController("YourServiceNameGoesHere");
        sc.Start();
    }
}
Run Code Online (Sandbox Code Playgroud)

安装程序完成后,安装项目将选择该类并运行您的服务.

  • 怎么样base.OnCommitted(...).需要调用吗? (7认同)
  • ServiceController实现了IDisposable.没有使用'using'关键字或故意调用Dispose方法? (3认同)
  • 您可以只使用Committed或AfterInstall事件,而不是创建新类.见下面的答案. (2认同)

and*_*nil 40

接受答案的小补充:

您也可以像这样获取服务名称 - 如果将来更改服务名称,可以避免任何问题:

protected override void OnCommitted(System.Collections.IDictionary savedState)
{
    new ServiceController(serviceInstaller1.ServiceName).Start();
}
Run Code Online (Sandbox Code Playgroud)

(每个安装程序都有一个ServiceProcessInstaller和一个ServiceInstaller.这里的ServiceInstaller称为serviceInstaller1.)


Kei*_*ith 23

此方法使用Installer类和最少量的代码.

using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;

namespace MyProject
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
            serviceInstaller1.AfterInstall += (sender, args) => new ServiceController(serviceInstaller1.ServiceName).Start();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

serviceInstaller1在Installer类设计器中定义(键入ServiceInstaller),并ServiceName在设计器中设置其属性.


小智 10

谢谢它运行OK ...

private System.ServiceProcess.ServiceInstaller serviceInstaller1;

private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
{
    ServiceController sc = new ServiceController("YourServiceName");
    sc.Start();
}
Run Code Online (Sandbox Code Playgroud)


小智 7

不要创建自己的类,而是在项目安装程序中选择服务安装程序,并向Comitted事件添加事件处理程序:

private void serviceInstallerService1_Committed(object sender, InstallEventArgs e)
{
    var serviceInstaller = sender as ServiceInstaller;
    // Start the service after it is installed.
    if (serviceInstaller != null && serviceInstaller.StartType == ServiceStartMode.Automatic)
    {
        var serviceController = new ServiceController(serviceInstaller.ServiceName);
        serviceController.Start();
    }
}
Run Code Online (Sandbox Code Playgroud)

仅当启动类型设置为自动时,它才会启动您的服务.