使用单个 EXE 部署多个 Windows 服务
在安装项目中设置 Windows 服务名称,
引言
我的项目需要将一个Windows服务EXE与不同的配置文件打包在一起,以便为不同的客户使用。本文将演示如何修改ProjectInstaller以支持此需求。
背景
我们公司有一个Windows服务产品。在部署给不同客户时,我们希望只给客户一个简单的Setup.exe(带有*.msi)以便于部署。我们希望使用不同的名称来安装Windows服务。
例如,对于客户ABC,安装后,Windows服务的名称将是“ABC Service”。
我们将使用相同的EXE打包不同的配置/数据文件。
Using the Code
在标准的Windows服务项目安装程序中,服务名称是在Sub InitializeComponent()
中设置的。Private Sub InitializeComponent()
' (other initialization code)
Me.ServiceInstaller1.ServiceName = "Service1"
'
End Sub
问题在于ServiceName
在service.exe中是硬编码的。安装项目将调用service.exe中的Project Installer,并使用Service1
作为Windows服务名称。我们希望在安装项目中选择名称。
因此,我们添加了一些代码来处理BeforeInstall
和BeforeUninstall
事件。
' Force Setup project to specify the service name in CustomActionData
' in "Install" Custom Install Action Developer should set the same name
' in CustomActionData in "Uninstall" Custom Install Action
Private Sub DoBeforeInstall(ByVal Sender As Object,
ByVal Args As System.Configuration.Install.InstallEventArgs)
Handles MyBase.BeforeInstall
' Context when Install
If GetContextParameter("SERVICENAME") = "" Then
Throw New Exception("SERVICENAME undefined")
End If
If Not Me.ServiceInstaller1 Is Nothing Then
Me.ServiceInstaller1.DisplayName = GetContextParameter(
"SERVICENAME")
Me.ServiceInstaller1.ServiceName = GetContextParameter(
"SERVICENAME")
End If
End Sub
' Developer should set the same name in CustomActionData in "Uninstall"
' Custom Install Action
Private Sub DoBeforeUninstall(ByVal Sender As Object,
ByVal Args As System.Configuration.Install.InstallEventArgs)
Handles MyBase.BeforeUninstall
' Context when Uninstall
If GetContextParameter("SERVICENAME") = "" Then
Throw New Exception("SERVICENAME undefined")
End If
Me.ServiceInstaller1.DisplayName = GetContextParameter("SERVICENAME")
Me.ServiceInstaller1.ServiceName = GetContextParameter("SERVICENAME")
End Sub
Public Function GetContextParameter(ByVal key As String) As String
Dim sValue As String = ""
If Me.Context Is Nothing Then
'WriteLog("Me.ServiceInstaller1 Is Nothing")
End If
Try
sValue = Me.Context.Parameters(key).ToString()
Return sValue
Catch
sValue = ""
Return sValue
End Try
End Function
在安装项目属性中,指定[ProductName]
。它将用作Windows服务名称(例如,DynamicService
)。
在自定义操作中,为自定义操作Install和Uninstall指定相同的SERVICENAME
。
运行安装程序,将安装一个名为DynamicService
的Windows服务。
关注点
- 对于在同一台机器上安装多个服务,每个安装程序应该具有不同的
[ProductCode]
和[UpgradeCode]
。 - 您还可以使用此技术更改Windows服务描述。