Source Generation
Arch Forum — 2026-02-12
Basics
- Generates code at compile time, with access to the same information as the compiler
- We already use it:
- Mapperly – object mapping
- Regex source generators – docs
Why is this good?
- Less boilerplate for common concerns (Firebase, mapping, regex)
- Generated code is just normal C# – compiled like everything else
- Slight performance advantage over runtime reflection
- Opens the door to AOT compilation
Problems with Castle.Core
- Handles things at runtime – hard to know what it does without debugging
- Even debugging is difficult to follow
- We are stuck on an old version; upgrading is risky because the code is hard to understand
- The overall .NET ecosystem trend is away from runtime reflection
Understanding & Debugging
Not everyone needs to understand the generator code itself.
Everyone can inspect the generated output – it’s plain C# – making debugging much easier.
Specifics
- Source generators are treated as Analyzers (even when they do more than analyze)
- The generator must target
netstandard2.0
- All dependencies must also support
netstandard2.0
- Debugging the generator itself is not perfectly straightforward
- Two main ways to emit code:
- Basic strings written to
.cs files (what we use – and the most popular method)
- Typed
SyntaxFactory
- Generators are additive only – they can add new code but never modify existing user code
Our Use Cases
- Firebase
- SqlRepository
- RestClient
- Controllers
Firebase Generator
~400 lines of code
- Find all interfaces that need code generated
- For each interface:
- Create a file named after the interface without the
I prefix, with a .g.cs extension
- Write class header (namespace, usings etc)
- Loop through methods & generate a method body for each
- Write class footer
SqlRepository Generator
- PR is done
- ~600 lines of code – ~200 lines less than the old Castle.Core implementation
- 1–2 days of AI-assisted work to write
- Haven’t inspected the generator code closely
- Not fully tested yet, but looks promising
When not to use a generator
Source generators are powerful, but in many cases it’s even more clear to just write the code directly.
Demo
- Look at the generator
- Look at the generated code