迁移至WiX Toolset 4与.NET 6.0,如何用代码安装Windows服务?
WiX Toolset 4 + .NET 6 下使用 ServiceProcessInstaller 实现服务安装的可行性
没问题!完全可以继续用你熟悉的ServiceProcessInstaller来实现服务安装,不用被迫切换到sc.exe。不过在WiX Toolset 4 + .NET 6的环境下,有几个关键点需要注意,我给你梳理清楚:
1. .NET 6 对 System.Configuration.Install 的支持
.NET 6 依然保留了System.Configuration.Install命名空间相关的类——只不过在.NET Framework里这个是系统自带的,而在.NET 5+(包括.NET 6)中,你需要手动安装对应的NuGet包才能使用ServiceProcessInstaller和ServiceInstaller。
安装包的命令很简单:
用Package Manager Console:
Install-Package System.Configuration.Install
或者用.NET CLI:
dotnet add package System.Configuration.Install
2. 与 WiX Toolset 4 的集成方式
WiX 4 依然支持通过**自定义动作(CustomAction)**调用.NET编写的安装逻辑,步骤如下:
第一步:编写自定义安装类
创建一个.NET 6类库项目,写一个继承自Installer的类,把ServiceProcessInstaller和ServiceInstaller的配置逻辑放进去:
using System.Configuration.Install; using System.ServiceProcess; [System.ComponentModel.RunInstaller(true)] public class MyServiceInstaller : Installer { public MyServiceInstaller() { // 配置服务进程账户 var processInstaller = new ServiceProcessInstaller { Account = ServiceAccount.LocalSystem, Password = null, Username = null }; // 配置服务本身的信息 var serviceInstaller = new ServiceInstaller { ServiceName = "YourDotNetFrameworkService", DisplayName = "你的.NET Framework服务", StartType = ServiceStartMode.Automatic, Description = "这是一个基于.NET Framework开发的Windows服务" }; // 添加到安装器集合 Installers.Add(processInstaller); Installers.Add(serviceInstaller); } }
第二步:在WiX项目中配置自定义动作
把编译好的类库引用到WiX项目里,然后在WiX的XML中定义自定义动作并绑定到安装序列:
<!-- 引用自定义安装程序集 --> <Binary Id="ServiceInstallerBin" SourceFile="..\MyServiceInstaller\bin\Release\net6.0\MyServiceInstaller.dll" /> <!-- 定义安装/卸载服务的自定义动作 --> <CustomAction Id="InstallService" BinaryKey="ServiceInstallerBin" DllEntry="Install" Execute="deferred" Impersonate="no" /> <CustomAction Id="UninstallService" BinaryKey="ServiceInstallerBin" DllEntry="Uninstall" Execute="deferred" Impersonate="no" /> <!-- 将动作加入安装/卸载序列 --> <InstallExecuteSequence> <!-- 安装文件后执行服务安装 --> <Custom Action="InstallService" After="InstallFiles" /> <!-- 卸载文件前执行服务卸载 --> <Custom Action="UninstallService" Before="RemoveFiles" /> </InstallExecuteSequence>
3. 几个关键注意事项
- 权限问题:一定要把自定义动作设置为
Execute="deferred"且Impersonate="no",因为服务安装需要管理员权限,延迟执行的动作会以系统权限运行,避免权限不足的问题。 - .NET Framework依赖:你的服务是基于.NET Framework编写的,记得在WiX项目中通过
NetFxExtension添加对目标.NET Framework版本的检测和安装逻辑,确保目标机器有运行环境。 - 参数传递(可选):如果需要动态传递服务名称、显示名称这类参数,可以通过WiX的
CustomActionData传递,在安装类里通过Context.Parameters来获取。
内容的提问来源于stack exchange,提问作者Tyrel Van Niekerk
相关产品推荐
相关产品推荐

