i am trying to make a Source Generator and up until the file generation everything seems to work fine.
When i attach a debugger i see it go trough the node filter and i am getting results as expected. But when i try to generate the code nothing seems to happen. While debugging it goes trough the GenerateCode method but there is no error nor exceptions. Here is the relevant code :
[Generator]
public class CustomGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
#if DEBUG
if (!Debugger.IsAttached)
{
Debugger.Launch();
SpinWait.SpinUntil(() => Debugger.IsAttached, 5000);
}
#endif
var attributes = context.SyntaxProvider.CreateSyntaxProvider(IsKnownAttribute, Static.GetDbAttributeOrNull).Where(t => t is not null).Collect();
#pragma warning disable CS8622 // Nullability of reference types in type of parameter doesn't match the target delegate (possibly because of nullability attributes).
context.RegisterSourceOutput(attributes, GenerateCode);
#pragma warning restore CS8622 // Nullability of reference types in type of parameter doesn't match the target delegate (possibly because of nullability attributes).
}
private static bool IsKnownAttribute(SyntaxNode syntaxNode, CancellationToken cancellationToken)
{
if (syntaxNode is not AttributeSyntax attribute)
{
return false;
}
var className = nameof(DbGenerationAttribute).Replace("Attribute", "");
return attribute.Name.ToString().Equals(className, StringComparison.OrdinalIgnoreCase)
|| attribute.Name.ToFullString().Equals(className, StringComparison.OrdinalIgnoreCase); ;
}
private static void GenerateCode(SourceProductionContext context, ImmutableArray<DbConnectionInfo> items)
{
context.AddSource("TestGen.g.cs", @"
namespace AtuomationDemo.SourceGeneration.Generated
{
public class MyClass
{
public static void PrintHello(string name)
{
System.Console.WriteLine($""Hello { name }!"");
}
}
}");
}
}
I tried adding the generator's attribute inside a .Net6 App (Rest API), but i kept getting a warning that an instance of the generator could not be found/created. I then moved it to a NetStandard2.0 class library but i am still not getting anything.
I tried looking for the generated files and found nothing. Also tried using the class that should have been generated but nothing came out of it.
Am i doing something wrong here?