I'm attempting to write a set of source generators to generate factory classes in a Blazor application.
The older examples all use ISourceGenerator which I believe has been superceded byIIncrementalGenerator.
The only good example I can find is the EnumGenerator (goes into any detail beyond the many posts that regurgitate the same trite and useless examples).
What I want is find all the classes that implement an interface, pull some information from them (maybe a class based attribute if I can't extract it any other way) and then generate a factory class. Old examples use context.Compilation.SyntaxTrees, but that approach is now outdated.
Here's some sample code:
[Generator]public class MySourceGenerator : IIncrementalGenerator{ public readonly record struct PresentationFactoryToGenerate { public readonly string Name; public readonly string Id; public readonly string Editor; public PresentationFactoryToGenerate(string name, string editor, string id) { this.Name = name; this.Editor = editor; this.Id = id; } } public void Initialize(IncrementalGeneratorInitializationContext context) { Debugger.Launch(); var presenters = Enumerable.Empty<PresentationFactoryToGenerate>(); // STUCK HERE // Get the list of presenters implementing IEditPresenter foreach (var presenter in presenters) context.RegisterPostInitializationOutput(ctx => ctx.AddSource($"{presenter.Name}EditPresenterFactory.g", SourceText.From(BuildPresenterFactory(presenter), Encoding.UTF8))); } private string BuildPresenterFactory(PresentationFactoryToGenerate item) { var code = $$""" namespace Blazr.App.Presentation; public class {{item.Name}}EditPresenterFactory { private readonly IServiceProvider _serviceProvider; public {{item.Name}}EditPresenterFactory(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public async ValueTask<IEditPresenter<{{item.Editor}}, {{item.Id}}}>> GetPresenterAsync({{item.Id}} id) { var presenter = ActivatorUtilities.CreateInstance<FarmEditPresenter>(_serviceProvider); ArgumentNullException.ThrowIfNull(presenter); await presenter.LoadAsync(id); return presenter; } }"""; return code; }}