c# - 如何通过 NuGet 包共享源代码以用于 .NET Core 项目

标签 c# visual-studio .net-core nuget csproj

我想制作一小段源代码(例如帮助程序类)以供在 .NET Core 项目 (.csproj) 中使用。 在这一点上,我根据不同的博客文章和官方 nuget 文档,以多种不同的方式用 NuGet 打包了源代码。我使用 nuspec 文件来控制我的源文件在 nuget 包中的最终位置,例如:

<files>
    <file src="*.cs" target="content/LruCache" />
    <file src="*.cs" target="contentFiles/cs/any/LruCache" />
</files>

我没有包含任何 msbuild 目标文件或安装脚本。

每当我将 NuGet 包安装到 .NET Core 项目 ( https://learn.microsoft.com/en-us/dotnet/core/tools/csproj ) 中时,我根本就没有得到任何东西。我的项目中不会包含任何源文件。我为 <PackageReference/> 尝试了不同的设置.csproj(PrivateAssets 等)中的节点没有成功。

这意味着可能吗?如果可以,应该怎么做?


背景:
这样做的原因是某种菱形继承(钻石问题),我们有项目 B 和 C 都使用辅助类 A,第三个项目 D 使用 B 和 C。 在这种情况下,当在 B 和 C 中使用不同(不兼容)版本的 A 时,我不想处理程序集版本冲突。

最佳答案

Is it meant to be possible at all? If so, how should it be done?

答案是肯定的。由于您测试的项目类型是 .net core。你应该使用 contentFiles而不是 content . content用于 packages.config。检查Using the contentFiles element for content files和博客 NuGet ContentFiles Demystified了解更多详情。

所以你的 .nuspec文件应该是:

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
  <metadata>
    <id>MyTestCore</id>
    <version>5.0.0</version>
    <authors>TestContentFile</authors>
    <owners>TestContentFile</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Package Description</description>
    <contentFiles>
      <files include="any/any/Test.cs" buildAction="content" flatten="true" copyToOutput="true"/>
    </contentFiles>
  </metadata>

  <files>
    <file src="contentFiles/any/any/Test.cs" target="contentFiles/any/any/LruCache" />
  </files>
</package>

nuget 包应该是这样的:

enter image description here

注意:当您创建一个新包时,不要忘记在 C:\Users\<UserName>\.nuget\packages 中删除该包的 nuget 缓存。文件夹,否则,它总是安装旧包。

enter image description here

使用此方法,源文件将包含到您的项目中。

希望这对您有所帮助。

关于c# - 如何通过 NuGet 包共享源代码以用于 .NET Core 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52880687/

相关文章:

C# File.ReadAllText 返回 "NotSupportedException"

c# - IHostedService/BackgroundService 按计划运行(与 Task.Delay 相反)

visual-studio - 我可以将 XML 文档从接口(interface)传播到其实现吗?

c# - Microsoft Dynamics 365 SDK 核心程序集 .NET Core 移植错误

c# - 如何在针对 .NET Core 的 Visual Studio 2015 中引用 System.Data?

c# - 事件 Azure Sql 连接数超过连接池限制

c# - Windows Phone 8 CommunicationException 远程服务器返回错误 : NotFound

c# - 使用 Visual Studio 2015 社区开发安全的 Android 和 iOS 应用程序,无需像 Xamarin 这样的第 3 方许可

visual-studio - 如何在 Visual Studio 中为当前选择交换剪贴板内容

visual-studio - Visual Studio 2010 Express 中的编译器的优化程度是否低于 Professional 版本的编译器?