Skip to content
altungaPublic

About

Full CQRS & Clean Architecture reference project in .NET 11 & C# 15 with source-generated Mediator, Riok.Mapperly, EF Core 11, FluentValidation, and caching pipelines.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

CommerceCqrs — .NET 11 & C# 15 Full CQRS Reference Project

CI .NET 11 C# 15 License: MIT

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.

Table of Contents


What Is CQRS?

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 —

Why CQRS Here?

  1. Interface Segregation (ISP): Query handlers only see IReadDbContext (read-only, non-tracking), so a query cannot accidentally call SaveChangesAsync() or mutate domain state. Command handlers depend only on the specific write repositories they need plus IUnitOfWork.
  2. Independent Optimization: Reads use AsNoTracking(), filtering, Skip/Take slicing, and distributed caching (IDistributedCache), while writes enforce domain invariants (Product.AdjustStock, Order.TransitionStatus) and audit timestamps (AuditableEntityInterceptor).
  3. Cross-Cutting Pipelines Without Boilerplate: Logging, validation, caching, and cache invalidation run automatically in Mediator pipeline behaviors—handlers stay focused on business logic.
  4. Explicit Use Cases: Every action is a first-class message (PlaceOrderCommand, AdjustProductStockCommand, GetProductsQuery, FindProductQuery, GetSalesDashboardQuery) organized by feature slice.

How a Request Flows Through CQRS

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&lt;T&gt; -> 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
Loading

Pipeline Execution Order (Program.cs)

  1. LoggingPipelineBehavior<,> — Logs start/completion using [LoggerMessage], measures duration via Stopwatch.GetTimestamp(), emits warnings for slow requests (> 500 ms), and logs Result failures.
  2. ValidationPipelineBehavior<,> — Executes all matching FluentValidation IValidator<TMessage> rules concurrently; failures throw AppValidationException, mapped by GlobalExceptionHandler to 400 HttpValidationProblemDetails.
  3. CachingPipelineBehavior<,> — Checks ICacheableQuery requests against IDistributedCache (AddDistributedMemoryCache()). Cache hits short-circuit before hitting EF Core; successful non-failure responses populate the cache and register under their CacheGroup.
  4. CacheInvalidationPipelineBehavior<,> — After an ICacheInvalidatingCommand succeeds, removes all declared CacheKeysToInvalidate and CacheGroupsToInvalidate (e.g., placing an order invalidates orders, products, and analytics).

CQRS Code Examples in This Repo

Write Side — Command + Cache Invalidation

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.

Read Side — Skip/Take Query + Distributed Caching

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;
}

Read Side — C# 15 Union Lookup (FindProductQuery)

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;
}

Solution & Feature Structure

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

Tech Stack & C# 15 Highlights

  • .NET 11 (net11.0) & C# 15 (<LangVersion>15</LangVersion>):
    • Union Types (union): Outcome<T>(OkValue<T>, Error) and ProductLookup(Guid, string) with exhaustive switch expressions.
    • Closed Hierarchies (closed): BaseEntity, AuditableEntity, and polymorphic Error (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] and PagedResult<T>[Index] alongside IsEmpty and HasMore.
    • field-Backed Properties & Primary Constructors: Input normalization on Category.Slug, Product.Sku, Product.Currency, Customer.Email, and Order.Currency.
  • 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, owned Address, and global soft-delete filters.
  • FluentValidation 12 (12.2.0) — Request validation pipeline.
  • Native OpenAPI + Scalar (2.21.0) — Interactive API docs at /scalar and OpenAPI JSON at /openapi/v1.json.

API Endpoints

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)

Seed Data Summary

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, and Platinum tiers
  • 150 Orders with 442 OrderItems, tier-based discounts, shipping calculations, and varied statuses

Running & Testing

# 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.Api

License

This project is licensed under the MIT License.

About

Full CQRS & Clean Architecture reference project in .NET 11 & C# 15 with source-generated Mediator, Riok.Mapperly, EF Core 11, FluentValidation, and caching pipelines.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages