Search code examples
c#.net-coremsbuildroslynanalyzer

Roslyn analyzer missing assembly warning


After creating a Roslyn analyzer package targeting .Net Standard 2.0, when I reference the package in another project, I receive the following error:

'C:\Users\username.nuget\packages\analyzer4\1.0.0.1\analyzers\dotnet\cs\Analyzer4.dll' depends on 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' but it was not found. Analyzers may not run correctly unless the missing assembly is added as an analyzer reference as well.

A repro of the project using the Analyzer is here. This repro is a vanilla .Net Core 2.0 console app with a reference to the analyzer and no other code whatsoever. The analyzer itself was built simply by creating the default Analyzer project in Visual Studio, changing it so that it targets netstandard2.0 instead of netstandard1.3, and then building in release mode to generate the .nupkg file. The analyzer does work properly, as the repro demonstrates, but the warning is generated.

There are discussions of this warning at various places on Github, such as here, but in those cases, the analyzer author had deliberately stripped out some local library code. In this case, the analyzer does not reference any other library.

I am not clear on what exactly it means to add an analyzer as an "analyzer reference" rather than just a regular project reference. I did try changing

<PackageReference Include="Analyzer4" Version="1.0.0.1" />

to

<Analyzer Include="..\LocalPackages\Analyzer4.1.0.0.1.nupkg" />

but that resulted in another error message ("PE image doesn't contain managed metadata").

Can anyone explain what this error means and ideally how to fix it?


Solution

  • You can use the approach in the Source Generators Cookbook (Thanks to @mbabramo for the link!).

    <ItemGroup>
    <PackageReference Include="Analyzer4" Version="1.0.0.1" />
    </ItemGroup>
    

    Becomes:

    <ItemGroup>
    <PackageReference Include="Analyzer4" Version="1.0.0.1" PrivateAssets="all" GeneratePathProperty="true" />
    <None Include="$(PkgAnalyzer4)\lib\netstandard2.0\*.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
    </ItemGroup>
    

    This should add the package dlls into your analyzer's folder, and it should work.