Search code examples
c#.netvisual-studioroslynsourcegenerators

Source Generator Running on Indirectly Associated Projects


I have built an incremental source generator and packaged it into a nuget package to be consumed by a different solution. I have referenced it in my 'Models' project. The issue is that the Models project is referenced by a lot of other projects in my solution. For some reason the source generator is running on each of these projects that reference my models project even though they do not reference the nuget package with my source generator. I want to know why this is, and how to stop it from happening.


Solution

  • I have found the answer which is pretty simple. Add PrivateAssets="all" to your package reference. In my case it looks like:

    <PackageReference Include="MapGenerator.Generator" Version="0.3.5-beta" PrivateAssets="all"/>

    I saw several places that said if you were packing a source generator as a nuget package, there weren't any additional considerations that needed to be made. This in my mind was a pretty big one though.

    In conclusion, if you want the source generator to run ONLY on the project that is referencing it, then you must add the PrivateAssets attribute.