使用dotnet pack将多个平台打包到一个软件包中

问题描述

我想创建一个包含两个具有不同平台(x86和x64)的版本的NuGet软件包。

我找到了使用“ nuget.exe MyProject.nuspec”执行此操作的解决方案。但是由于我的项目有很多依赖关系,因此手动编写.nuspec很复杂并且容易出错。

一种更干净的方法是使用“ dotnet pack MyProject.csproj”。所有依赖项都会自动添加。我目前的方法如下:

msbuild MyProject.csproj -p:Configuration=Release -p:Platform="x86"
msbuild MyPeoject.csproj -p:Configuration=Release -p:Platform="x64"

dotnet pack MyProject.csproj -c Release -p:Platform="x86" --no-build -o ./
dotnet pack MyProject.csproj -c Release -p:Platform="x64" --no-build -o ./

结果是一个包含x64版本的软件包(我猜x86被x64覆盖了)。

我正在寻找的东西是这样的:

msbuild MyProject.csproj -p:Configuration=Release -p:Platform="x86"
msbuild MyPeoject.csproj -p:Configuration=Release -p:Platform="x64"

dotnet pack MyProject.csproj -c Release -p:Platform="x86|x64" --no-build -o ./

是否有一个参数将两个内部版本打包到一个软件包中?

解决方法

如果定位到多个平台,则需要手动将配置添加到csproj。此配置包含要添加到nuget程序包中的dll的源路径以及nuget程序包中的目标文件夹。

将此项目组添加到您的csproj:

<ItemGroup>
    <None Include="bin\x64\Release\net48\MyProject.dll" Pack="true" PackagePath="build\net48\x64\MyProject.dll" />
    <None Include="bin\x86\Release\net48\MyProject.dll" Pack="true" PackagePath="build\net48\x86\MyProject.dll" />
</ItemGroup>

此外,您需要添加一个.target文件,以告诉nuget消耗项目哪些dll需要从nuget程序包复制到其输出文件夹。此.target文件还包括仅在x86和x64平台上起作用的检查。这里不支持MSIL。

MyProject.targets的内容:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <Target Name="PlatformCheck_MyProject" BeforeTargets="InjectReference_MyProject" Condition="(('$(Platform)' != 'x86') and  ('$(Platform)' != 'x64'))">
        <Error  Text="$(MSBuildThisFileName) does not work correctly on '$(Platform)' platform. You need to specify platform 'x86' or 'x64'." />
    </Target>
    <Target Name="InjectReference_MyProject" BeforeTargets="ResolveAssemblyReferences">
        <ItemGroup>
            <Reference Include="MyProject">
                <HintPath>$(MSBuildThisFileDirectory)..\..\build\$(TargetFramework)\$(Platform)\MyProject.dll</HintPath>
            </Reference>
        </ItemGroup>
    </Target>
</Project>

将这些行添加到csproj中,还将.target文件添加到nuget包中:

<ItemGroup>
    <Content Include="MyProject.targets" Pack="true" PackagePath="build\MyProject.targets" />
</ItemGroup>

将此配置添加到项目中后,即可使用dotnet进行构建和打包:

dotnet build MyProject.csproj -c=Release /p:Platform=x64 --no-incremental
dotnet build MyProject.csproj -c=Release /p:Platform=x86 --no-incremental
dotnet pack MyProject.csproj --no-build -c=Release -o=./