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
- Packaging a Roslyn Analyzer with NuGet package references
- Multi-targeting a Roslyn analyzer (this post)
A Roslyn Analyzer must target .NET Standard 2.0. However, you may want to target a more recent framework such as .NET 5.0 to take advantages of the Nullable Reference Types. While Nullable Reference Types work with libraries targeting .NET Standard 2.0, older targets cannot take advantage of the framework annotations. So, you'll get lots of meaningless warnings. You can read my previous post for more details.
The idea is to build both targets and only include the .NET Standard 2.0 DLL into the published package. The final NuGet package content should look like:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <!-- Multi-target the library. Must contain at least "netstandard2.0" --> <TargetFrameworks>net5.0;netstandard2.0</TargetFrameworks> <Nullable>enable</Nullable> <!-- https://docs.microsoft.com/en-us/nuget/reference/nuspec#developmentdependency --> <developmentDependency>true</developmentDependency> <!-- Do not include the dll into the NuGet package, we'll add it manually at the right location --> <IncludeBuildOutput>false</IncludeBuildOutput> <NoPackageAnalysis>true</NoPackageAnalysis> </PropertyGroup> <ItemGroup> <!-- Include the netstandard2.0 DLL into the package --> <None Include="$(OutputPath)\netstandard2.0\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" /> </ItemGroup> <!-- 👇 disable the nullable warnings when compiling for .NET Standard 2.0 --> <PropertyGroup Condition="'$(TargetFramework)' == 'netstandard2.0'"> <NoWarn>$(NoWarn);nullable</NoWarn> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.CodeAnalysis" Version="3.8.0" /> </ItemGroup> </Project>
You can now use the .NET CLI to build the package:
dotnet pack --configuration Release
Do you have a question or a suggestion about this post? Contact me!