Referencing an analyzer from a project
This post is part of the series 'Roslyn Analyzers'. Be sure to check out the rest of the blog posts of the series!
- Writing a Roslyn analyzer
- Writing language-agnostic Roslyn Analyzers using IOperation
- Working with types in a Roslyn analyzer
- Referencing an analyzer from a project (this post)
- Packaging a Roslyn Analyzer with NuGet package references
- Multi-targeting a Roslyn analyzer
- Roslyn analyzers: How to
- How to test a Roslyn analyzer
- Useful resources to write Roslyn Analyzers
Once you have created a Roslyn Analyzer, you have multiple ways to consume it in your project:
- Using a Visual Studio extension
- Using a NuGet package
- Using a Project Reference when the Roslyn Analyzer is in the same solution
The first 2 solutions are the most common ones, and are described in the first post of the series: Writing a Roslyn Analyzer. For instance, here's an example of referencing an analyzer from a NuGet package:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Meziantou.Analyzer" Version="1.0.427">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>
However, the last solution is not the most common one, but it is very convenient when the analyzer is useful only for the current solution:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Analyzer1\Analyzer1.csproj"
PrivateAssets="all"
ReferenceOutputAssembly="false"
OutputItemType="Analyzer"
SetTargetFramework="TargetFramework=netstandard2.0" />
</ItemGroup>
</Project>
You can also create a file named Directory.Build.props
to declare the analyzer for all projects of the solution:
<Project>
<ItemGroup>
<!-- Use MSBuildThisFileDirectory to make the path relative to the current file location -->
<ProjectReference Include="$(MSBuildThisFileDirectory)\Analyzer1\Analyzer1.csproj"
PrivateAssets="all"
ReferenceOutputAssembly="false"
OutputItemType="Analyzer" />
</ItemGroup>
</Project>
Thanks Nick Craver for the tip: https://twitter.com/Nick_Craver/status/1256365611455840256
Do you have a question or a suggestion about this post? Contact me!