2

我有一个 netstandard2.0 csproj(我们称之为 MyPackage),它在构建时(由 GeneratePackageOnBuild 指定)打包到一个 nuget 包中。这个 nuget 包在构建目录中有自定义的道具和目标(因此引用项目会导入这些)。

我在同一个解决方案中有另一个项目(我们称之为 MyConsumer)来测试 MyPackage。我希望 MyConsumer 在构建时从 MyPackage 导入构建资产道具和目标,就像它作为来自某个远程 nuget 源的 PackageReference 一样使用它。

我怎样才能得到这个工作(最简单)?

我已经能够通过一个非常复杂的方法来做到这一点,我让 MyConsumer 将 PackageReference 添加到 MyPackage 并覆盖 MyConsumer 中的 RestoreSources 以指向 MyPackage 的 bin 目录。当运行 dotnet build 或 Visual Studio build 的 sln 时,这会变得非常奇怪,因为项目元数据是在还原期间为所有项目预先生成的,因此此时 MyPackage 不存在。解决方案是在 MyConsumer 项目中添加对 MSBuild 的嵌套调用,但这变得更糟,因为 Visual Studio 还原的操作与 dotnet build 执行的自动还原完全不同。

有什么简单的方法可以做到这一点吗?

这就是我现在所拥有的

<Project> 
  <Target Name="Build">    
    <Message Text="Running inner build" Importance="high" />

    <!-- 
    Need to call MSBuild twice, once to restore, then again to restore and build to get the restore of the Sdk to work
    because of this bug in MSBuild: https://github.com/Microsoft/msbuild/issues/2455
    Note the trailing Prop=1 is required to get MSBuild to invalid it's cache of the project target imports
    -->
    <MSBuild Projects="$(MSBuildProjectFullPath)" Targets="Restore" Properties="Configuration=$(Configuration);Version=$(Version);IsInnerBuild=true;Prop=1" />
    <!-- Have to use dotnet build instead of another call to MSBuild because of another bug that prevents proper imports within the same physical process  -->
    <Exec Command="dotnet build /p:Configuration=$(Configuration) /p:Version=$(Version) /p:IsInnerBuild=true" />
    <Message Text="Finished inner build" Importance="high" />
  </Target>

  <Target Name="Restore" />

  <Target Name="RemoveBin">
    <RemoveDir Directories="bin" />
  </Target>

  <!-- Don't do real cleans old rebuild since it breaks MSBuild due to the same above bug -->
  <Target Name="Rebuild" DependsOnTargets="RemoveBin;Build">
  </Target>
</Project>
4

1 回答 1

2

将 ProjectReference 视为 PackageReference 或允许 PackageReference 到本地 csproj

如果我理解你是正确的,你想用 project 生成包MyPackage,然后将它安装到测试项目MyConsumer中,并在构建时从 MyPackage 导入构建资产道具和目标。

要实现这个目标,您需要完成以下几件事:

  • 确保项目在项目MyPackage之前构建MyConsumer
  • 将包设置为打包器源
  • 在构建期间将包添加MyPackage.nupkg到测试项目。MyConsumer

以上详情:

  • 确保项目在项目MyPackage之前构建MyConsumer

由于您要测试项目生成的MyConsumer包,所以在测试项目使用它之前,您应该确保该包已运行,因此我们需要设置项目MyConsumer引用该项目MyPackage

  • 将包设置为打包器源

您可以使用项目的构建后事件MyPackage将包复制MyPackage.nupkg到本地提要,或者您可以将 bin 目录添加MyPackage.nupkg到包源中。

  • 在构建期间将包添加MyPackage.nupkg到测试项目。MyConsumer

使用 VS 2017 和PackageReference测试项目的样式,您可以在解决方案的根目录中MyConsumer设置一个文件,其中包含您需要的测试项目:Directory.Build.propsMyConsumer

<Project>
  <ItemGroup>
    <PackageReference Include="MyPackage" Version="1.0.* />
  </ItemGroup>
</Project>

这会将这些 NuGet 包添加到MyConsumer解决方案中的测试项目中,它将用作来自某个远程 nuget 源的 PackageReference。

查看马丁的答案以获取更多详细信息。

希望这可以帮助。

于 2018-05-14T15:00:58.470 回答