C# Source Generator - warning CS8032: An instance of analyzer cannot be created
Asked Answered
M

8

59

I'm trying to build a Source Generator. Right now, just the most basic static method that returns "Hello World".

The generator project builds, but the generated code is not available, the debugger never starts, and the build output shows

CSC : warning CS8032: An instance of analyzer Generator.StaticPropertyEnum.helloWorld cannot be created from ...\bin\Debug\net5.0\Generator.StaticPropertyEnum.dll : Could not load file or assembly 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified..

Examples I'm referencing

I've tried

  • changing the TargetFramework and LanguageVersion of both the generator and test projects
  • referencing many version of the analyzer libraries Microsoft.CodeAnalysis.CSharp and Microsoft.CodeAnalysis.Analyzers
  • referencing an explicit version of Microsoft.Net.Compilers.Toolset
  • Adding an explicit reference to the NetStandard library
  • starting from scratch with an analyzer project template
  • looking for a generator project template (but didn't find one)

Versions

Visual Studio: version 16.8.3
.NET SDK: 5.0.101

Code

Generator.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.9.0-2.final" PrivateAssets="all" />
    <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.0.0" PrivateAssets="all" />
  </ItemGroup>
 
</Project>

Test csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>

    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
    <PackageReference Include="xunit" Version="2.4.1" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="coverlet.collector" Version="1.3.0">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
  </ItemGroup>

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

</Project>

Generator

    [Generator]
    public class helloWorld : ISourceGenerator
    {
        public void Execute(GeneratorExecutionContext context)
        {


            context.AddSource("HelloWorld-generated.cs", @"
            using System;
            namespace HelloWorld
            {
                public static class Hello
                {
                    public static string SayHello() {
                        return ""HelloWorld"";
                    }
                }
            }");
        }

        public void Initialize(GeneratorInitializationContext context)
        {
#if DEBUG
            if(!Debugger.IsAttached) Debugger.Launch();
#endif
        }
    }
Medici answered 28/12, 2020 at 15:21 Comment(0)
S
19

Source Generators must be .NET Standard 2.0 to run in Visual Studio 2019+ or .NET Standard 1.x to run in Visual Studio 2017+.

Savagery answered 28/12, 2020 at 15:31 Comment(6)
Hmm. I'm sure I'd tried that. The build succeeded once I also downgraded Microsoft.CodeAnalysis.CSharp to 3.8.0. Intellisense still thinks it's broken though.Medici
For intelisense try closing and reopening VSSavagery
Ah. I had to delete the .vs folderMedici
@Medici - Finally! I'm very new to source generators and absolutely could not get it to work until I downgraded from 3.9.0 to 3.8.0. Very helpful tip, thanks!Preordain
Downgrading from 3.10 to 3.8.0 also helped on my end - unsure what root cause isChickie
Different version of visual studio support different version of Microsoft.CodeAnalysis.CSharp. If you're using an earlier version of VS, you'll need an earlier version of Microsoft.CodeAnalysis.CSharp.Savagery
P
20

As crazy as it is

  1. Close and reopen Visual Studio (2019, 2022)
  2. If step 1 did NOT work, delete .vs folder

That solved my problem

Perreira answered 16/5, 2022 at 15:55 Comment(2)
Also worked for me, until I rebuild the solution for the second time. :-(Calabria
Thanks!! I changed my source generator's TargetFramework and it didn't help until I restarted & deleted .vs & restarted again.Darmstadt
S
19

Source Generators must be .NET Standard 2.0 to run in Visual Studio 2019+ or .NET Standard 1.x to run in Visual Studio 2017+.

Savagery answered 28/12, 2020 at 15:31 Comment(6)
Hmm. I'm sure I'd tried that. The build succeeded once I also downgraded Microsoft.CodeAnalysis.CSharp to 3.8.0. Intellisense still thinks it's broken though.Medici
For intelisense try closing and reopening VSSavagery
Ah. I had to delete the .vs folderMedici
@Medici - Finally! I'm very new to source generators and absolutely could not get it to work until I downgraded from 3.9.0 to 3.8.0. Very helpful tip, thanks!Preordain
Downgrading from 3.10 to 3.8.0 also helped on my end - unsure what root cause isChickie
Different version of visual studio support different version of Microsoft.CodeAnalysis.CSharp. If you're using an earlier version of VS, you'll need an earlier version of Microsoft.CodeAnalysis.CSharp.Savagery
H
10

I have source generator that targets netstandard2.0 and net5.0 for nullability support.

 <TargetFrameworks>net5.0;netstandard2.0</TargetFrameworks>
 <Nullable>enable</Nullable>

and sample library that targets same frameworks.

It crashes when project is being built within Visual Studio, but builds ok from the terminal.

To solve this, I've changed target framework when referencing it as a generator with SetTagetFramework and now it compiles without any warnings or errors.

  <ItemGroup>
    <ProjectReference Include="..\MyGenerator\MyGenerator.csproj"
                      OutputItemType="Analyzer" ReferenceOutputAssembly="false"
                      SetTargetFramework="TargetFramework=netstandard2.0" />
  </ItemGroup>
Harberd answered 19/3, 2021 at 4:6 Comment(5)
FYI: You don't need .NET 5 for nullability support. The attributes aren't included in .net standard, but they can be added via the nuget package Nullable. If you don't want to use the nuget package, you can grab the sources from its Git repoTantalize
@MikeChristiansen, I know that, but runtime libraries aren't annotated in netstandard2.0, so I may get NRE in FirstOrDefault or IsNullOrEmpty won't check nullabilityHarberd
Fair point. This is one of those cases where ReSharper or Rider can help. First, they have additional nullability analysis, including "optimistic" and "pessimistic" modes. If you set it to pessimistic, then any method/property not marked with nullable attributes will be assumed to return null, and accept not null.Tantalize
Additionally, Rider and ReSharper have a feature to apply nullability (among others) attributes to external code. So, even if .NET Standard doesn't include the nullability attributes, you can still "add" them - albeit only for IDE usage, and only those that use Rider/ReSharper. On top of that, ReSharper/Rider ships with a robust set of built-in external annotations for .NET Standard/Core/Framework code that isn't annotated by defaultTantalize
this answer was it for me. when including an analyzer from the self same solution as the project[s] consuming it, though the analyzer project utilized .net 6 within it's own project for development, you must consume the analyzer as netstandard 2.0.Gametophore
P
8

as @Yair-Halberstadt mentioned in a different answer, the specific error listed is due to the fact that currently source generator projects need to target netstandard2.0. However if you get the CS8032 error with a different assembly (for example Microsoft.CodeAnalysis, Version=3.0.x ...) your problem is probably caused by a SDK version mismatch. For example on my computer I have SDK 5.0.302 which has version 3.10.0 of Microsoft.CodeAnalysis and Microsoft.CodeAnalysis.CSharp. While the Generator project uses nuget to get these packages, the build of the project referencing the generator resolves these files from the SDK. This is why reverting to 3.8.0 has worked for some commentators, the SDK version they have installed contains 3.8.0 of these references.

Pushing answered 2/9, 2021 at 17:15 Comment(4)
I'm curious if there is a way to make this work regardless though. I'm assuming probably not since analyzers run from Roslyn, which is the compiler, which is part of the SDK. So they will always run from the SDK, which makes it version-dependent. Do you know of any way to work around that so that it works regardless of specific versions of dotnet SDK installed?Proser
@duu82 I am not aware of any way, but have not tried. there may be something you can do with assembly version redirects, but I am not sure how useful that would be.Pushing
accepted answer with Microsoft.Net.Compilers here solve the issue for meBainmarie
Adding Microsoft.Net.Compilers solved the issue for me tooGuffaw
I
3

I had to downgrade from 4.0.0 to 3.9 CodeAnalysis Sharp and Analyzers.

Itinerate answered 20/11, 2021 at 10:52 Comment(1)
Can you tell us why? Which version of VS are you using? Which framework version?Parabasis
I
1

Warning CS8032

In my case I got this warning CS8032 in Visual Studio 2022:

##[warning]CSC(0,0): Warning CS8032: An instance of analyzer Microsoft.EntityFrameworkCore.InternalUsageDiagnosticAnalyzer cannot be created from C:\Windows\ServiceProfiles\NetworkService.nuget\packages\microsoft.entityframeworkcore.analyzers\7.0.2\analyzers\dotnet\cs\Microsoft.EntityFrameworkCore.Analyzers.dll : Could not load file or assembly 'Microsoft.CodeAnalysis, Version=4.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified..

The issue

In my project, I have had 2 packages from Microsoft.EntityFrameworkCore.SqlServer and Microsoft.EntityFrameworkCore.InMemory installed with the latest version 7.0.2, but my TargetFramework for the project was net6.0.

The solution

Target Framework and Package versions must be identical. So I have chosen to downgrade my packages to 6.0.x and the warning CS8032 disappeared.

Note

The same solution applies to Target Framework counterpart Installed Packages.

Illuminator answered 24/1, 2023 at 6:7 Comment(0)
R
0

Removing my nuget package and adding the LAST stable version fixed that issue for me.

Respectability answered 30/10, 2022 at 23:16 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Pacien
S
-1

I could solve the same problem with

git clean -xdf

and then rebuilding the entire solution.

Sukin answered 2/11, 2022 at 9:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.