7

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.

4

1 回答 1

2

我在GitHub 上收到了这个问题的答案。

库项目具有对生成器项目的以下引用就足够了:

  <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>

(我不确定 Remove 行是否有任何作用。这可能是不必要的。)

当库作为 NuGet 包使用时,生成器会自动作为分析器包含在内,即分析器引用是可传递的。

但是,当通过项目引用(例如在库自己的单元测试项目中)使用库时,我们需要以下内容:

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

原始帖子中的示例都处理项目引用。不幸的是,从我收集到的信息来看,对分析器的传递项目引用似乎是不可能的。

于 2021-10-04T07:58:35.270 回答