Building Smart API Endpoints with CSharp Source Generators
π§ Introduction
In modern .NET development, we often find ourselves repeating the same patterns to expose CRUD operations for our models. Yes, frameworks like ASP.NET Core simplify things with conventions and routing helpers, but what if we could go further? What if we could:
β
Auto-generate endpoints
β
Integrate with Entity Framework
β
Avoid writing any boilerplate
β
Customize behaviors when needed
Thatβs where Roslyn Source Generators come in. In this post, Iβll show you how I built a powerful yet flexible tool called AutoApiGenerator, capable of generating full REST endpoints at compile-time, just by annotating your entity classes with an attribute.
π The [AutoApi]
Attribute
Letβs start simple. Hereβs the attribute that tells the generator what to process:
π Highlights:
Property | Description |
---|---|
RoutePrefix | Controls the base route for generated endpoints |
DbContextType | Enables EF Core support for database operations |
ποΈ Generator Architecture
The generator pipeline is structured in a clean, composable way:
Discover entity classes decorated with
[AutoApi]
Analyze their syntax and semantic models
Generate two files per entity:
*.gen.cs
β fully auto-generated base CRUD endpoints*.cs
β partial class to allow custom extension
𧬠Architecture Diagram:
βοΈ Source Generator Code Breakdown
1. π Initialization Phase
2. π§ Endpoint Generation Logic
ποΈ EF Core Integration
If a DbContextType
is specified, the generator automatically includes full EF-backed CRUD:
π¨βπ¬ EF Core Features:
Supports async operations
Uses DI for
DbContext
Handles ID-based lookups for
GET /{id}
,PUT
, andDELETE
π§© Customization via Partial Classes
Your own logic can coexist with the generated one using partials:
π Comparative Table
Approach | Boilerplate | Customizable | Type-safe | Compile-time |
---|---|---|---|---|
Manual CRUD Controllers | β High | β Yes | β Yes | β No |
Minimal APIs with Hand Coding | β οΈ Medium | β Yes | β Yes | β No |
π₯ AutoApiGenerator | β Very Low | β Yes (partials) | β Yes | β Yes |
β Key Benefits
π Why Use AutoApiGenerator?
π‘ 90% less boilerplate β No more repetitive controller code
π§ Type-safe β Backed by Roslynβs compiler-level analysis
π οΈ Customizable β Extend or override any part with partials
ποΈ EF Core Ready β Auto-queries your
DbContext
π§Ύ Predictable β Pure compile-time, no hidden runtime behavior
π Final Thoughts
This pattern highlights the real strength of Roslyn Source Generators:
πΌ Professional-grade APIs with minimal effort
π Consistency across all endpoints
βοΈ Automation without sacrificing flexibility
Whether you're building admin panels, internal tools, or just speeding up prototyping β this generator saves time while improving code quality.
π¦ GitHub Repository
Want to try it yourself or contribute?
π View the full source on GitHub