Reputation: 113
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:
Create a solusion with a console application, then add a class library project. Both projects are .NET 5.
Install NuGet package Microsoft.CodeAnalysis.CSharp.Workspaces
for both projects.
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) {
}
}
}
In the Main method of console application, write following code:
GeneratedNamespace.GeneratedClass.GeneratedMethod();
In the .csproj of the console application, add following code:
<ItemGroup>
<ProjectReference Include="..\ClassLibrary_ExperimentalSourceGenerator\ClassLibrary_ExperimentalSourceGenerator.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
</ItemGroup>
Build solution.
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.
Upvotes: 5
Views: 2248
Reputation: 311315
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...'
Upvotes: 6