I have a Source Generator, it looks like this:
public class Generator : ISourceGenerator
{
public Generator()
{
// Uncomment if you want to debug this
Debugger.Launch();
}
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(() => new MySyntaxReceiver());
}
public void Execute(GeneratorExecutionContext context)
{
var syntaxReceiver = (MySyntaxReceiver)context.SyntaxReceiver;
var responseMessageClasses = syntaxReceiver.ResponseMessageClasses;
// do stuff to responseMessageClasses
}
}
internal class MySyntaxReceiver : ISyntaxReceiver
{
public List<ClassDeclarationSyntax> ResponseMessageClasses { get; private set; } = new List<ClassDeclarationSyntax>();
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
if (syntaxNode is ClassDeclarationSyntax cds &&
cds.Identifier.ValueText.EndsWith("ResponseMessage", StringComparison.OrdinalIgnoreCase))
{
ResponseMessageClasses.Add(cds);
}
}
}
In the same project, I have a folder of simple classes of which the name all ends with "ResponseMessage". These classes only have simple types like string, int and bool as properties. They are in a different namespace than the SourceGenerator.
There's a second console app project that references my source generator as an Analyzer. When I build the project I can succesfully break into the SourceGenerator code.
The problem: the simple ResponseMessage classes never get seen by the SyntaxReceiver class I have. The OnVisitSyntaxNode
method only hits the Program.cs file. What is going on?
By design, it's not possible to use a source generator in the assembly where it was defined. According to the design spec:
Generator implementations are defined in external assemblies passed to the compiler using the same
-analyzer:
option used for diagnostic analyzers....
Since generators are loaded from external assemblies, a generator cannot be used to build the assembly in which it is defined.