简体   繁体   中英

How to run C# source generator in visual studio?

Recently I am updating my self to learn this new technology, however I cannot get the source generator running even I followed step-by-step to tutorial.

What I have done:

  1. Create a solusion with a console application, then add a class library project. Both projects are .NET 5.

  2. Install NuGet package Microsoft.CodeAnalysis.CSharp.Workspaces for both projects.

  3. In the class library project, write following code:

     using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using System.Text; namespace ClassLibrary { [Generator] public class MySourceGenerator: ISourceGenerator { public void Execute(GeneratorExecutionContext context) { context.AddSource("myGeneratedFile.cs", SourceText.From(@" namespace GeneratedNamespace { public class GeneratedClass { public static void GeneratedMethod() { // generated code } } }", Encoding.UTF8)); } public void Initialize(GeneratorInitializationContext context) { } } }
  4. In the Main method of console application, write following code:

     GeneratedNamespace.GeneratedClass.GeneratedMethod();
  5. In the.csproj of the console application, add following code:

     <ItemGroup> <ProjectReference Include="..\ClassLibrary_ExperimentalSourceGenerator\ClassLibrary_ExperimentalSourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" /> </ItemGroup>
  6. Build solution.

  7. Recieve following error:

    CS0103
    The name 'GeneratedNamespace' does not exist in the current context ConsoleApp1 D:\OneDrive\VS Solutions\ConsoleApp1\Program.cs

    And following warning:

    CS8032
    An instance of analyzer ClassLibrary.MySourceGenerator cannot be created from D:\OneDrive\VS Solutions\ClassLibrary_ExperimentalSourceGenerator\bin\Debug\net5.0\ClassLibrary_ExperimentalSourceGenerator.dll: Could not load file or assembly 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. System cannot find the file specified.

I believe the problem here is that your source generator assembly targets .NET 5.

Source generators must target netstandard2.0 in order to work correctly within Visual Studio. This is because VS runs net48 internally, so it cannot load code targeting newer frameworks.

The hint here is the error message:

Could not load file or assembly 'System.Runtime, Version=5.0.0.0...'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM