如何将源代码生成器作为 NuGet 引用添加?

3

如何将Source Generator作为NuGet包添加到C# net5项目中?

要将项目添加为源生成器,可以使用以下代码:

<ItemGroup>
  <ProjectReference Include="..\xyz.SourceGenerators\xyz.SourceGenerators.csproj"
    OutputItemType="Analyzer"
    ReferenceOutputAssembly="false"
    SetTargetFramework="TargetFramework=netstandard2.0" />
</ItemGroup>

然而,我正在寻找XMLPackageReference以将Nuget包添加为源生成器。


1
只需像添加其他软件包一样添加即可。 - canton7
@canton7 <PackageReference Include="xyz.SourceGenerators" Version="1.0.0"> 对我来说不起作用。生成器没有被执行。 - Fritz
1
那么就有其他问题了:你引用它是正确的。 - canton7
1
请查看 https://dev59.com/s1EG5IYBdhLWcg3wgPt3,这可能会对您有所帮助。 - Alexandru Clonțea
1
@AlexandruClonțea,你猜对了,问题是由于错误的 NuGet 包引起的。 - Fritz
1个回答

4

我已经得出解决方案。感谢您在评论中提供的提示。

<PackageReference Include="xyz.SourceGenerators" Version="1.0.0">

只需要添加一个包含源代码生成器的Nuget包即可。

但是,您需要正确地将生成器添加到Nuget包中。为此,请将以下行添加到Nuget包的.csproj文件中。

<ItemGroup>
  <None Include="$(OutputPath)\netstandard2.0\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
</ItemGroup>

解决方案来源:如何打包 C# 9 源代码生成器并上传到 Nuget?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接