如何在启动服务exe期间找到我的服务名称

时间:2012-08-07 11:04:29

标签: c# windows service

我想部署一个提供Web服务的exe,并且可以多次启动它(每个作为单独的Windows服务)。 exe的每个实例都需要能够加载不同的配置文件(例如,它可以在不同的端口上侦听,或者使用不同的数据库)。

理想情况下,我不想在多个文件夹中安装exe,只需要有多个配置文件。

然而,似乎没有办法找到Windows正在启动的服务名称。

我看过了 How can a Windows Service determine its ServiceName? 但它似乎对我不起作用,因为在启动期间,启动服务的进程ID为0。

我想我太早要求了什么。我的代码执行以下操作:

Main设置当前目录并构造WebService对象(ServiceBase的子类)

WebService对象构造函数现在需要设置其ServiceName属性,并使用How can a Windows Service determine its ServiceName?中的代码尝试查找正确的名称。但是,此时正确的服务名称的processid仍为0。

在此之后,Main将构建一个包含WebService对象的(1)ServiceBase数组,并在数组上调用ServiceBase.Run。此时服务名称必须正确,因为一旦服务运行,它可能不会更改。

1 个答案:

答案 0 :(得分:0)

在阅读https://stackoverflow.com/a/7981644/862344

之后,我找到了另一种实现目标的方法

在安装webservice期间,安装程序(恰好是同一个程序,但命令行参数为“install”)知道要使用哪个设置文件(因为有一个命令行参数“设置=“)。

链接的问题显示,通过覆盖Installer类的OnBeforeInstall(和OnBeforeUninstall)方法,有一种简单的方法可以在每次启动时将该命令行参数传递给服务。

protected override void OnBeforeInstall(System.Collections.IDictionary savedState) {
    if (HasCommandParameter("settings")) {
        // NB: Framework will surround this value with quotes when storing in registry
        Context.Parameters["assemblypath"] += "\" \"settings=" + CommandParameter("settings");
    }
    base.OnBeforeInstall(savedState);
}

protected override void OnBeforeUninstall(System.Collections.IDictionary savedState) {
    if (HasCommandParameter("settings")) {
        // NB: Framework will surround this value with quotes when storing in registry
        Context.Parameters["assemblypath"] += "\" \"settings=" + CommandParameter("settings");
    }
    base.OnBeforeUninstall(savedState);
}

我发现框架中的某些东西在 Context.Parameters [“assemblypath”] 值中包含引号,然后将其存储在注册表中(在 HKLM \ System \ CurrentControlSet \ Services \ \ ImagePath ),因此有必要在现有值(即exe路径)和参数之间添加“”“”。

相关问题