51

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
        }
    }
farlee2121
  • 2,959
  • 4
  • 29
  • 41

8 Answers8

17

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+.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
Yair Halberstadt
  • 5,733
  • 28
  • 60
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>
farlee2121
  • 2,959
  • 4
  • 29
  • 41
JL0PD
  • 3,698
  • 2
  • 15
  • 23
  • 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](https://www.nuget.org/packages/Nullable/). If you don't want to use the nuget package, you can grab the sources from [its Git repo](https://github.com/manuelroemer/Nullable) – Mike Christiansen Apr 16 '22 at 18:46
  • @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 nullability – JL0PD Apr 17 '22 at 02:27
  • 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](https://www.jetbrains.com/help/resharper/Code_Analysis__Value_Analysis.html#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. – Mike Christiansen Apr 17 '22 at 17:11
  • Additionally, Rider and ReSharper have a feature to apply nullability (among others) attributes to [external code](https://www.jetbrains.com/help/rider/Code_Analysis__External_Annotations.html). 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](https://github.com/JetBrains/ExternalAnnotations/tree/master/Annotations) for .NET Standard/Core/Framework code that isn't annotated by default – Mike Christiansen Apr 17 '22 at 17:15
  • 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. – user4893106 Jun 16 '22 at 02:16
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.

  • 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? – Duu82 Jan 19 '22 at 20:51
  • @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. – Andrew Moskevitz Jan 21 '22 at 13:16
  • 1
    accepted answer with Microsoft.Net.Compilers [here](https://stackoverflow.com/questions/54370683/why-cant-microsoft-analyzers-find-microsoft-codeanalysis) solve the issue for me – Yochai Lehman Jul 03 '22 at 12:16
  • 1
    Adding Microsoft.Net.Compilers solved the issue for me too – user487779 Jul 14 '22 at 10:24
8

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

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
3

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

Frank
  • 903
  • 7
  • 14
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.

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
0

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

  • 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](/help/how-to-answer). – Community Nov 02 '22 at 17:05
-1

I could solve the same problem with

git clean -xdf

and then rebuilding the entire solution.

Masoud
  • 65
  • 9