问题描述
我正在使用 dotnet pack
命令为以下场景创建 NuGet 包:
项目结构:
Project B
|----> Project A
Project A
|----> SomePackage
我想创建一个包含 ProjectB.dll
、ProjectA.dll
和 SomePackage
作为 NuGet 包依赖项的 NuGet 包。
为了将 ProjectA.dll
作为 NuGet 包的一部分(而不是包依赖性),我使用了以下建议 here 的解决方案。
在ProjectB.csproj
中:
<ProjectReference Include="ProjectA.csproj" PrivateAssets="all"/>
<PropertyGroup>
<TargetsForTfmSpecificBuildOutput>$(TargetsForTfmSpecificBuildOutput);copyProjectReferencesToPackage</TargetsForTfmSpecificBuildOutput>
</PropertyGroup>
<Target Name="copyProjectReferencesToPackage" DependsOnTargets="BuildOnlySettings;ResolveReferences">
<ItemGroup>
<!-- Filter out unnecessary files -->
<_ReferencecopyLocalPaths Include="@(ReferencecopyLocalPaths->WithMetadataValue('ReferenceSourceTarget','ProjectReference')->WithMetadataValue('PrivateAssets','All'))"/>
</ItemGroup>
<!-- Print batches for debug purposes -->
<Message Text="Batch for .nupkg: ReferencecopyLocalPaths = @(_ReferencecopyLocalPaths),ReferencecopyLocalPaths.Destinationsubdirectory = %(_ReferencecopyLocalPaths.Destinationsubdirectory) Filename = %(_ReferencecopyLocalPaths.Filename) Extension = %(_ReferencecopyLocalPaths.Extension)" Importance="High" Condition="'@(_ReferencecopyLocalPaths)' != ''" />
<ItemGroup>
<!-- Add file to package with consideration of sub folder. If empty,the root folder is chosen. -->
<BuildOutputInPackage Include="@(_ReferencecopyLocalPaths)" TargetPath="%(_ReferencecopyLocalPaths.Destinationsubdirectory)"/>
</ItemGroup>
</Target>
问题:
当我运行 dotnet pack ProjectB.csproj
时,我得到一个包含 ProjectA.dll 和 Project B.dll 的包,但不依赖于 SomePackage
。
问题:
如何将 SomePackage
的依赖项添加到 ProjectB
NuGet 包?
可能的解决方案:
这两种方法的缺点:我需要为 ProjectA
使用的每个 NuGet 包添加依赖项,这很容易忘记和破坏。
解决方法
您已将 PrivateAssets="all"
用于项目 A,这意味着其传递依赖项是私有的,主项目 B 无法访问。我们通常使用它来禁用引用项目的依赖项。
所以如果您使用它,您将无法从引用的项目中获取传递依赖项。并且它会将项目A变成一个程序集dll,并使其失去nuget包及其传递依赖项的能力。
如果你还想实现目标,你应该注意这些:
1) 直接将项目 A 的 csproj 中的 PackageReference
节点等传递依赖复制到项目 B 的 csproj 中。
<PackageReference Include="SomePackage" Version="*.*.*" />
......
在这种情况下,您不必使用 ProjectB.nuspec
或 nuget 包管理器 UI。
2) 放弃对项目 A 使用 PrivateAssets="all"
并将项目 A 作为 nuget 包。确保其 nuget 功能的完整性。
除此之外,别无他法。