This post is part of the series 'Roslyn Analyzers'. Be sure to check out the rest of the blog posts of the series!
Once you have created a Roslyn Analyzer, there are 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 two options are the most common and are described in the first post of the series: Writing a Roslyn Analyzer. Here is an example of referencing an analyzer from a NuGet package:
csproj (MSBuild project file)
<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>
The third option is less common, but very convenient when the analyzer is only needed within the current solution:
csproj (MSBuild project file)
<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 in the solution:
csproj (MSBuild project file)
<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!