Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.
  • The source generator itself shouldn't be required to install separately from the original NuGet package.

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.

Why it is such a big deal to ship the Source Generator with the library? The SG's will produce code which is required for library itself.

I might have skipped something while reading through the docs, however I am just unable to figure it out, assuming this is even possible.

like image 556
Twenty Avatar asked Oct 15 '22 00:10

Twenty


1 Answers

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.

<ItemGroup>
    <None Include="Path\To\SourceGenerator\bin\$(Configuration)\netstandard2.0\NameOfSourceGenerator.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
</ItemGroup>
like image 193
Twenty Avatar answered Nov 15 '22 05:11

Twenty