A production-structured .NET 11 & C# 15 Full CQRS and Clean Architecture reference solution for ASP.NET Core Minimal APIs. Built with compile-time source-generated martinothamar/Mediator v3, Riok.Mapperly entity/model mapping, Entity Framework Core 11, FluentValidation, Distributed Memory Caching (IDistributedCache), structured [LoggerMessage] logging pipelines, C# 15 union & closed types, SOLID principles, and deterministic relational seed data.
- What Is CQRS?
- How a Request Flows Through CQRS
- CQRS Code Examples in This Repo
- Solution & Feature Structure
- Tech Stack & C# 15 Highlights
- API Endpoints
- Seed Data Summary
- Running & Testing
- License
CQRS (Command Query Responsibility Segregation) is an architectural pattern that separates state-mutating operations (Commands) from data-reading operations (Queries) instead of routing every use case through a single CRUD service and shared DTOs.
In traditional N-tier CRUD, reads and writes share the same service methods, validation assumptions, tracking behavior, and models—making queries bloated and writes harder to guard. CQRS splits them cleanly:
| Dimension | Commands (Write Side) | Queries (Read Side) | Notifications (Events) |
|---|---|---|---|
| Intent | Change system state | Return data without side effects | React to something that happened |
| Mediator Contract | ICommand<Result> / ICommand<Result<T>> |
IQuery<Result<T>> |
INotification |
| Handler Contract | ICommandHandler<TCommand, TResponse> |
IQueryHandler<TQuery, TResponse> |
INotificationHandler<TNotification> |
| Persistence Access | I*WriteRepository + IUnitOfWork (tracked entities) |
IReadDbContext (AsNoTracking() queryables) |
Logging / side-effect orchestration |
| Mapping (Mapperly) | Command → Entity (ToEntity) or ApplyUpdate |
Entity → Model (ToModel / ToModelList) |
— |
| Validation | FluentValidation via ValidationPipelineBehavior |
Query parameter validation (Skip, Take, sort, ranges) |
— |
| Caching | ICacheInvalidatingCommand evicts keys/groups on success |
ICacheableQuery reads/populates IDistributedCache |
— |
- Interface Segregation (ISP): Query handlers only see
IReadDbContext(read-only, non-tracking), so a query cannot accidentally callSaveChangesAsync()or mutate domain state. Command handlers depend only on the specific write repositories they need plusIUnitOfWork. - Independent Optimization: Reads use
AsNoTracking(), filtering,Skip/Takeslicing, and distributed caching (IDistributedCache), while writes enforce domain invariants (Product.AdjustStock,Order.TransitionStatus) and audit timestamps (AuditableEntityInterceptor). - Cross-Cutting Pipelines Without Boilerplate: Logging, validation, caching, and cache invalidation run automatically in
Mediatorpipeline behaviors—handlers stay focused on business logic. - Explicit Use Cases: Every action is a first-class message (
PlaceOrderCommand,AdjustProductStockCommand,GetProductsQuery,FindProductQuery,GetSalesDashboardQuery) organized by feature slice.
Every HTTP request enters a Minimal API endpoint, dispatches a message through compile-time source-generated IMediator, passes through four ordered IPipelineBehavior<TMessage, TResponse> stages, and executes either the read path or the write path:
flowchart LR
HTTP["HTTP Request (Minimal API)"] --> MED["IMediator (Source-Generated)"]
MED --> LOG["1. LoggingPipelineBehavior"]
LOG --> VAL["2. ValidationPipelineBehavior (FluentValidation)"]
VAL --> CACHE["3. CachingPipelineBehavior (ICacheableQuery)"]
CACHE -- "Cache Hit" --> RES["Result / Outcome<T> -> HTTP"]
CACHE -- "Cache Miss / Command" --> INV["4. CacheInvalidationPipelineBehavior"]
INV --> SPLIT{"Query or Command?"}
SPLIT -- "IQuery" --> QH["QueryHandler -> IReadDbContext (AsNoTracking) -> Mapperly ToModel"]
SPLIT -- "ICommand" --> CH["CommandHandler -> Domain Entity + WriteRepo + IUnitOfWork"]
CH -- "Success" --> NOTIF["Publish INotification (e.g., OrderPlacedNotification)"]
CH --> EVICT["Evict Cache Groups on Success"]
QH --> RES
EVICT --> RES
LoggingPipelineBehavior<,>— Logs start/completion using[LoggerMessage], measures duration viaStopwatch.GetTimestamp(), emits warnings for slow requests (> 500 ms), and logs Result failures.ValidationPipelineBehavior<,>— Executes all matching FluentValidationIValidator<TMessage>rules concurrently; failures throwAppValidationException, mapped byGlobalExceptionHandlerto400 HttpValidationProblemDetails.CachingPipelineBehavior<,>— ChecksICacheableQueryrequests againstIDistributedCache(AddDistributedMemoryCache()). Cache hits short-circuit before hitting EF Core; successful non-failure responses populate the cache and register under theirCacheGroup.CacheInvalidationPipelineBehavior<,>— After anICacheInvalidatingCommandsucceeds, removes all declaredCacheKeysToInvalidateandCacheGroupsToInvalidate(e.g., placing an order invalidatesorders,products, andanalytics).
public sealed record CreateProductCommand(
string Sku,
string Name,
string Description,
decimal Price,
string Currency,
int StockQuantity,
int ReorderLevel,
decimal WeightKg,
bool IsActive,
bool IsFeatured,
Guid CategoryId)
: ICommand<Result<ProductModel>>, ICacheInvalidatingCommand
{
public IReadOnlyCollection<string> CacheGroupsToInvalidate => [CacheGroups.Products, CacheGroups.Analytics];
}CreateProductCommandHandler checks SKU uniqueness via IProductWriteRepository, maps the command to a Product entity with IProductMapper.ToEntity(command) (Riok.Mapperly), persists via IUnitOfWork, and returns Result<ProductModel>. Upon success, CacheInvalidationPipelineBehavior clears cached products and analytics entries.
public sealed record GetProductsQuery(
int Skip = 0,
int Take = 20,
Guid? CategoryId = null,
string? Search = null,
decimal? MinPrice = null,
decimal? MaxPrice = null,
bool? LowStockOnly = null,
bool? FeaturedOnly = null,
string SortBy = "name",
bool SortDesc = false)
: IQuery<Result<PagedResult<ProductModel>>>, ICacheableQuery
{
public string CacheKey =>
$"products:list:skip={Skip}:take={Take}:cat={CategoryId}:q={Search}:min={MinPrice}:max={MaxPrice}:low={LowStockOnly}:feat={FeaturedOnly}:sort={SortBy}:desc={SortDesc}";
public string CacheGroup => CacheGroups.Products;
}public union ProductLookup(Guid, string);
public sealed record FindProductQuery(ProductLookup Lookup)
: IQuery<Result<ProductModel>>, ICacheableQuery
{
public string CacheKey => Lookup switch
{
Guid id => $"products:id:{id}",
string sku => $"products:sku:{sku.Trim().ToUpperInvariant()}"
};
public string CacheGroup => CacheGroups.Products;
}Every type (class, record, interface, enum, union) lives in its own file:
src/
├── CommerceCqrs.Domain/ # Pure C# entities, value objects, enums, domain invariants (zero NuGet deps)
├── CommerceCqrs.Application/ # CQRS vertical slices, Mediator behaviors, Mapperly mappers, FluentValidation
│ ├── Common/
│ │ ├── Behaviors/ # Logging, Validation, Caching, CacheInvalidation pipeline behaviors
│ │ ├── Caching/ # ICacheService, ICacheableQuery, ICacheInvalidatingCommand, CacheGroups
│ │ ├── Extensions/ # C# 15 extension blocks & indexers (PagedResultExtensions)
│ │ ├── Mapping/ # Riok.Mapperly interfaces & partial mappers
│ │ ├── Models/ # PagedResult<T>(Items, Skip, Take, TotalCount)
│ │ ├── Persistence/ # IReadDbContext (read), IWriteRepository<T> & IUnitOfWork (write)
│ │ └── Results/ # Result, Result<T>, Outcome<T> union, closed Error hierarchy
│ └── Features/
│ └── <Feature>/ # Analytics, Categories, Customers, Orders, Products
│ ├── Commands/ # Command records
│ ├── Queries/ # Query records
│ ├── Handlers/ # Command, Query, and Notification handlers
│ ├── Validators/ # FluentValidation validators
│ ├── Models/ # Read models & request/union types
│ └── Notifications/ # Domain/application INotification events
├── CommerceCqrs.Infrastructure/ # EF Core AppDbContext, audit interceptor, write repos, DistributedCacheService, seeder
└── CommerceCqrs.Api/ # Minimal API endpoint modules, GlobalExceptionHandler, OpenAPI/Scalar, DI composition
tests/
└── CommerceCqrs.Tests/ # Unit tests (C# 15 features, Mapperly, validators, behaviors) & API integration tests
- .NET 11 (
net11.0) & C# 15 (<LangVersion>15</LangVersion>):- Union Types (
union):Outcome<T>(OkValue<T>, Error)andProductLookup(Guid, string)with exhaustiveswitchexpressions. - Closed Hierarchies (
closed):BaseEntity,AuditableEntity, and polymorphicError(NotFoundError,ConflictError,ValidationError,FailureError) enabling exhaustive pattern matching across assemblies without fallback arms. - Collection Expression Arguments (
[with(...)]):[with(StringComparer.OrdinalIgnoreCase), ...]and[with(capacity: ...)]. - Extension Indexers &
extension(...)Blocks:PagedResult<T>[int]andPagedResult<T>[Index]alongsideIsEmptyandHasMore. field-Backed Properties & Primary Constructors: Input normalization onCategory.Slug,Product.Sku,Product.Currency,Customer.Email, andOrder.Currency.
- Union Types (
- martinothamar/Mediator v3 (
3.0.2) — Compile-time source-generated CQRS mediator and pipeline dispatch. - Riok.Mapperly v4 (
4.3.1) — Compile-time Entity ↔ Model and update-in-place mapping. - Entity Framework Core 11 (
11.0.0) — SQLite persistence,AuditableEntityInterceptor, ownedAddress, and global soft-delete filters. - FluentValidation 12 (
12.2.0) — Request validation pipeline. - Native OpenAPI + Scalar (
2.21.0) — Interactive API docs at/scalarand OpenAPI JSON at/openapi/v1.json.
| Group | Endpoints |
|---|---|
| Categories | GET /api/categories, GET /api/categories/{id}, POST /api/categories, PUT /api/categories/{id}, DELETE /api/categories/{id} |
| Products | GET /api/products?skip=0&take=20&..., GET /api/products/{id}, GET /api/products/by-sku/{sku}, GET /api/products/low-stock, POST /api/products, PUT /api/products/{id}, PATCH /api/products/{id}/stock, DELETE /api/products/{id} |
| Customers | GET /api/customers?skip=0&take=20&..., GET /api/customers/{id}, POST /api/customers, PUT /api/customers/{id}, DELETE /api/customers/{id} |
| Orders | GET /api/orders?skip=0&take=20&..., GET /api/orders/{id}, POST /api/orders, PATCH /api/orders/{id}/status |
| Analytics | GET /api/analytics/dashboard |
| Docs & Health | GET /health, GET /openapi/v1.json, GET /scalar (Development) |
On first startup, DatabaseSeeder deterministically populates SQLite using Bogus:
- 12 Categories
- 120 Products (10 per category, including low-stock and featured items)
- 60 Customers across
Standard,Silver,Gold, andPlatinumtiers - 150 Orders with 442 OrderItems, tier-based discounts, shipping calculations, and varied statuses
# Build
dotnet build CommerceCqrs.slnx --configuration Release
# Run all 23 unit & integration tests
dotnet test CommerceCqrs.slnx --configuration Release --no-build --verbosity normal
# Run the API (starts with Scalar UI at /scalar and OpenAPI at /openapi/v1.json)
dotnet run --project src/CommerceCqrs.ApiThis project is licensed under the MIT License.