What a source generator is
In many cases, we find ourselves writing the same kind of code repeatedly. In the past, I have used T4 templates to generate code and even written stored procedures and applications that can help me generate code. Source generators are part of the .NET compiler platform (Roslyn) SDK.
A generator gives us access to a compilation object representing all the user code currently being compiled. From there, the object can be inspected, and we can, based on that, write additional code.
Okay, this sounds complicated, and I would be lying if I said it was easy to write a source generator, but it instantly saves us a lot of time. So, let’s break it down a bit.
When we compile our code, the compiler does the following steps:
- The compilation runs.
- Source generators analyze code.
- The source generators generate new code.
- The compilation continues.
Steps 2 and 3 are what source generators do.
In Blazor, source...