【问题标题】:How can I find my service name during startup of a service exe如何在服务 exe 启动期间找到我的服务名称
【发布时间】:2012-08-08 18:13:58
【问题描述】:

我想部署一个提供 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? 中的代码来尝试找到正确的名称。但是此时正确的servicename的processid还是0。

接着,Main 将构建一个包含 WebService 对象的 (1) ServiceBase 数组,并在该数组上调用 ServiceBase.Run。此时服务名称需要正确,因为一旦服务运行,它可能无法更改。

【问题讨论】:

    标签: c# windows service


    【解决方案1】:

    在阅读https://stackoverflow.com/a/7981644/862344后,我找到了实现目标的替代方法

    在安装 web 服务期间,安装程序(恰好是同一个程序,但带有“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路径)和参数之间加上'" "'。

    【讨论】:

      猜你喜欢
      • 2015-11-28
      • 2011-06-08
      • 2012-10-20
      • 1970-01-01
      • 1970-01-01
      • 2021-01-07
      • 2019-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多