Windows 服务 - 如何使名称可配置 [英] Windows service - how to make name configurable

查看:33
本文介绍了Windows 服务 - 如何使名称可配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 C# 编写了一个 Windows 服务.一开始的要求是我应该只运行该服务的一个实例,但现在已经改变了,现在我需要多个实例.这就是为什么我需要根据配置文件更改服务名称.

I have written a windows service in C#. The requirement at the beginning was that I should be running only one instance of that service, but that has changed and now I need multiple instances. This is why I need to change the service name according to the configuration file.

使用正确名称注册的最佳方法是什么?我应该编写另一个工具来做到这一点吗?我可以从 App.config 文件中读取名称并相应地在服务和安装程序类中设置它吗?

What would be the best way to make it register with the correct name ? Should I write another tool to do it? Can I just read the name from App.config file and set it in the service and installer classes accordingly ?

PS> 我不太明白带名称的东西是如何工作的 - 应该在服务和安装程序类中设置名称,但是当使用 installutil.exe 甚至 powershell new-service 安装时,也应该指定名称.一定要一样吗?或者一个覆盖另一个?

PS> I do not really understand how that thing with names work - one should set names in service and installer classes, but then when installing with installutil.exe or even powershell new-service the name also should be specified. Does that have to be the same? Or one overrides another?

推荐答案

您可以简单地从 app.config 中读取它并在安装程序类中进行设置.
通常,会自动创建一个继承自 Installer 的类.它包含一个 System.ServiceProcess.ServiceInstaller 类型的成员,很可能名为 serviceProcessInstaller1.这有一个属性 ServiceName 可以设置.此外,您需要设置 ServiceNameServiceBase 派生类的 code> 属性为相同的值.
在默认实现中,它们在各自的 InitializeComponent 方法中被设置为常量值,但没有理由坚持这一点.可以动态完成,没有问题.

You can simply read it from the app.config and set it in the installer classes.
Normally, a class that inherits from Installer is automatically created. It contains a member of type System.ServiceProcess.ServiceInstaller, most likely named serviceProcessInstaller1. This has a property ServiceName you can set. Additionally, you need to set the ServiceName property of the ServiceBase derived class to the same value.
In a default implementation, these are set to constant values in the respective InitializeComponent methods, but there is no reason to stick with this. It can be done dynamically without problems.

这篇关于Windows 服务 - 如何使名称可配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆