Reflection is slow. It happens at runtime, bypasses type safety, and prevents trimming. Source Generators solve this by generating code at compile time. In this guide, we build a generator that automatically implements a `MapTo` method for DTOs, replacing AutoMapper.
The Goal
[AutoMap(typeof(UserEntity))]
public partial class UserDto
{
public string Username { get; set; }
}
// Generated Code should look like:
partial class UserDto
{
public void MapFrom(UserEntity entity)
{
this.Username = entity.Username;
}
}
The Generator Logic
[Generator]
public class MapperGenerator : ISourceGenerator
{
public void Execute(GeneratorExecutionContext context)
{
var syntaxReceiver = (MySyntaxReceiver)context.SyntaxReceiver;
foreach (var classDecl in syntaxReceiver.CandidateClasses)
{
// Analyze properties using Roslyn Semantic Model
// Generate StringBuilder content
context.AddSource($"{className}_Map.g.cs", sourceText);
}
}
}
Key Takeaways
- Source Generators enable **Zero-Overhead abstractions**.
- They are essential for **Native AOT** compatibility.
- Debug them by setting `<IsRoslynComponent>true</IsRoslynComponent>`.
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.