Source Generator only annotate method instead of class
Is it possible to annotate only a method with a custom attribute instead of the class itself?
HasAttribute
is a custom method which simply checks for the attribute, for classes it works just fine - for method it does not.. Would that be the right way? Assuming that HasAttribute
works fine for methods too10 Replies
Are you asking for how to only process methods annotated with an attribute?
yes I wanna look up for methods annotated with [CustomAttribute]
Scrap everything you've done so far
Use incremental source generators and
ForAttributeWithMetadataName
https://github.com/dotnet/roslyn/blob/main/docs/features/incremental-generators.md covers incremental generators
ForAttributeWithMetadataName
is one of the methods on SyntaxValueProvider
. The method is brand new and not directly covered in the above document, but is very similar to CreateSyntaxProvider
, which is covered
That method was designed for exactly this scenario, and will make it both significantly easier and significantly faster
Literally 100x faster than trying to do this manually
Also, #roslyn exists for asking questions about source generators and the like 🙂Alright I'll give it a shot - thank you very very much for the quick explanation, I didn't even know about the existence of incremental source generators
ISourceGenerator
was the V1. It had some unfixable perf problems, so IIncrementalSourceGenerator
s were created
As long as you're using VS 2022.3, you'll have access to ForAttributeWithMetadataName
If you're in VS 2019, you will have to continue using ISourceGenerator
But also, upgrade!Ah got it, I've noticed that the code always gets regenerated even if nothing changed.. is some kind of memoization possible to implement?
That would be one of the unsolvable perf problems in V1 🙂
I am using the latest VS2022, so thats fine :P
IIncrementalSourceGenerator
and ForAttributeWithMetadataName
were designed specifically to make this fast and run as little as possibleThat's awsome! Gotta love the source gens they make your life so much easier in larger apps