简体   繁体   English

在面向使用者代码的 NuGet 库中使用源生成器

[英]Using Source Generators in a NuGet library targeting consumer code

I am trying to move a lot of my runtime reflection stuff to AOT with the new Source Generators, however I am facing a few issues.我正在尝试使用新的源生成器将我的很多运行时反射内容移动到 AOT,但是我面临一些问题。 Let me first talk through the requirements I have.先说一下我的要求吧。

  • The code of the library needs to target .NET 5, but not for the Source Generator itself, although it would be a nice to have, but according to the MS dev-blog it is not yet possible.该库的代码需要针对 .NET 5,但不是针对 Source Generator 本身,尽管拥有它会很好,但根据MS 开发者博客,目前还不可能。
  • The source generator itself shouldn't be required to install separately from the original NuGet package.源生成器本身不需要与原始 NuGet 包分开安装。

Now to a more visual example, imagine package A to be the NuGet library which should contain code for the user of the package A. Package B, the package containing the source generators which again should be executed on the users code-base and not on package A. Package B should be shipped with package A.现在来看一个更直观的例子,假设包 A 是 NuGet 库,它应该包含包 A 的用户的代码。包 B,包含源生成器的包,这些源生成器再次应该在用户代码库上执行,而不是在包装 A。包装 B 应与包装 A 一起运输。

Why it is such a big deal to ship the Source Generator with the library?为什么将 Source Generator 与库一起交付如此重要? The SG's will produce code which is required for library itself. SG 将生成库本身所需的代码。

I might have skipped something while reading through the docs, however I am just unable to figure it out, assuming this is even possible.我可能在阅读文档时跳过了一些东西,但是我只是无法弄清楚,假设这甚至是可能的。

It actually turned out to be easier than expected.事实证明它比预期的要容易。 It is possible to ship the Source Generator in the same NuGet package by referencing it as an Analyzer with the PackagePath argument in the .csproj file of the parent project.通过在父项目的 .csproj 文件中将 Source Generator 引用为具有PackagePath参数的 Analyzer,可以在同一个 NuGet 包中传送源生成器。

<ItemGroup>
    <None Include="Path\To\SourceGenerator\bin\$(Configuration)\netstandard2.0\NameOfSourceGenerator.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
</ItemGroup>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM