Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a Roslyn Analyzer project a transitive dependency?

I have a library that relies on a source generator to work correctly. In the MyLibrary.csproj, I reference the generator like so.

<ItemGroup>
  <ProjectReference 
        Include="..\MyLibrary.Generators\MyLibrary.Generators.csproj" 
        PrivateAssets="contentfiles;build"
        ReferenceOutputAssembly="false"
        OutputItemType="analyzer"/>
</ItemGroup>

I need this analyzer reference to be transitive, i.e. projects that reference MyLibrary should get the MyLibrary.Generators analyzer transitively.

A simple reference like so does not seem to reference the analyzer, only MyLibrary

<ProjectReference Include="..\MyLibrary\MyLibrary.csproj" />

I want to stress that I am not looking for MyLibrary.Generators to be consumed as a regular assembly reference, but as a Roslyn Analyzer so my source generator can run as intended during compile time.

like image 266
chyyran Avatar asked Feb 23 '21 07:02

chyyran


1 Answers

I have received an answer to this question on GitHub.

It is sufficient for the library project to have the following reference to the generator project:

  <ItemGroup>
    <!-- Package the generator in the analyzer directory of the nuget package -->
    <None Remove="$(OutputPath)/$(AssemblyName).Generator.dll" />
    <None Include="$(OutputPath)/$(AssemblyName).Generator.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
  </ItemGroup>

(I am not sure if the Remove line does anything. It might be unnecessary.)

When the library is consumed as a NuGet package, the generator is automatically included as an analyzer, i.e. the analyzer reference is transitive.

However, when the library is consumed through a project reference (such as in the library's own unit test project), we need the following:

  <ItemGroup>
    <ProjectReference Include="..\MyLibrary\MyLibrary.csproj" />
    <ProjectReference Include="..\MyLibrary.Generator\MyLibrary.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
  </ItemGroup>

The examples in the original post all handle project references. From what I have gathered, a transitive project reference to an analyzer seems impossible, unfortunately.

like image 83
Timo Avatar answered Oct 20 '22 21:10

Timo