WPF项目命令行发布遇ResolveComReference错误及GitHub Actions部署问题
问题背景
我通常使用Visual Studio 2022的「发布选择」功能发布WPF项目,设置为win-x86、any-cpu、自包含模式,一切正常。现在想通过GitHub仓库和GitHub Actions实现自动化部署,尝试了以下命令:
dotnet publish --configuration Release --self-contained true --runtime win-x86 --output ./published
但无论在GitHub Actions中用run: <命令>执行,还是本地用cmd运行,都会报错:
The task "ResolveComReference" is not supported on the .NET Core version of MSBuild. Please use the .NET Framework version of MSBuild
尝试了两种解决方案但均无效:
- 修改
.csproj文件,添加以下配置:
<PropertyGroup> <IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract> <TargetFramework>net6.0-windows</TargetFramework> </PropertyGroup>
- 替换为msbuild命令:
dotnet msbuild -v:normal -p:Configuration=RELEASE,在GitHub Actions中执行时出现错误:
Assets file 'D:\a\SES\SES\SES\obj\project.assets.json' not found. Run a NuGet package restore to generate this file. [D:\a\SES\SES\SES\SES.csproj]
本地执行则再次出现之前的ResolveComReference错误。
疑问
- 问题的根本原因是什么?
- 为什么在Visual Studio中发布不会失败?
- 如何通过命令行正确发布,以在GitHub Actions中使用?
解决方案与解答
1. 问题的根本原因
你的WPF项目引用了COM组件,而.NET Core版本的MSBuild不支持ResolveComReference这个任务——dotnet publish和dotnet msbuild默认调用的都是.NET Core版MSBuild,所以触发了这个错误。另外,你用dotnet msbuild时未先执行NuGet还原,导致缺少project.assets.json文件,这是第二个错误的原因。
2. Visual Studio发布不失败的原因
Visual Studio针对WPF这类依赖.NET Framework特性的项目做了适配:当检测到项目包含COM引用时,会自动切换到**.NET Framework版本的MSBuild**(路径一般是C:\Program Files (x86)\Microsoft Visual Studio\2022\<Edition>\MSBuild\Current\Bin\MSBuild.exe)来处理发布流程,自然能正确执行ResolveComReference任务。
3. 命令行与GitHub Actions的正确发布方式
本地命令行发布
直接调用.NET Framework版的MSBuild执行发布,命令示例(根据你的VS版本和安装路径调整):
"C:\Program Files (x86)\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\MSBuild.exe" YourProject.csproj ^ /t:Publish ^ /p:Configuration=Release ^ /p:SelfContained=true ^ /p:RuntimeIdentifier=win-x86 ^ /p:PublishDir=./published
GitHub Actions自动化部署配置
使用windows-latest runner,先配置VS环境,执行NuGet还原,再调用MSBuild发布:
name: WPF自动发布 on: [push] jobs: publish: runs-on: windows-latest steps: - name: 拉取代码 uses: actions/checkout@v4 - name: 设置VS环境 uses: microsoft/setup-msbuild@v2 - name: NuGet包还原 run: nuget restore YourProject.csproj - name: 发布项目 run: msbuild YourProject.csproj /t:Publish /p:Configuration=Release /p:SelfContained=true /p:RuntimeIdentifier=win-x86 /p:PublishDir=./published
注意:将YourProject.csproj替换为你实际的项目文件名。
内容的提问来源于stack exchange,提问作者Jannes

