architecture-cqrs

Clean Architecture layers, CQRS with MediatR, thin controllers, pipeline behaviors, Mapster, module boundaries and per-resource authorization for a layered .NET backend. Use when editing C# in the Application, Api or Core projects: commands, queries, handlers, validators, controllers, or cross-module code.

Qu'est-ce que architecture-cqrs ?

architecture-cqrs is a Claude Code agent skill that clean Architecture layers, CQRS with MediatR, thin controllers, pipeline behaviors, Mapster, module boundaries and per-resource authorization for a layered .NET backend. Use when editing C# in the Application, Api or Core projects: commands, queries, handlers, validators, controllers, or cross-module code.

Compatible avec~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/19mittal/dotnet-next-toolkit/tree/HEAD/plugins/dotnet-backend/skills/architecture-cqrs

Installed? Explore more Développement et programmation skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Architecture & CQRS


0. Project context

Resolve once per session, from the working directory: the solution (*.sln / *.slnx, else *.csproj — ask if several match) and its projects by role: <Api>, <Application>, <Core>, <Infrastructure>, <Tests>. Those placeholders mean the real project names; paths below are relative to the solution root. Take product names from the repo — never invent one. If the solution is not layered this way, say so and ask before imposing this structure.


1. Clean Architecture — Layer Rules

The solution is structured into four immutable layers. Dependency flow is strictly inward: Web → Application → Core ← Infrastructure

LayerResponsibilityForbidden
CoreEntities, Enums, Interfaces (IRepository<T>, IUnitOfWork, service contracts)References to any other layer
ApplicationMediatR Commands/Queries/Handlers, FluentValidation Validators, DTOs, Mapster configDirect DB access, HTTP, Refit
InfrastructureEF Core DbContext, Repositories, UoW, Refit clients, DelegatingHandlers, JWTMediatR, Application DTOs
WebControllers, Program.cs, Middleware, OpenAPI/Swagger configBusiness logic of any kind

Violations that must never occur:

  • A Controller containing any logic beyond await _mediator.Send(command).
  • An Application handler using any Infrastructure namespace.
  • A Core entity referencing Application or Infrastructure types.

2. CQRS with MediatR

Command / Query Naming

Features/
  <BoundedContext>/
    Commands/
      <ActionName>Command/
        <ActionName>Command.cs          ← IRequest<TResult>
        <ActionName>CommandValidator.cs ← AbstractValidator<TCommand>
        <ActionName>CommandHandler.cs   ← IRequestHandler<TCommand, TResult>
    Queries/
      <QueryName>Query/
        <QueryName>Query.cs
        <QueryName>QueryHandler.cs
    DTOs/
      <Entity>Response.cs

Handler Rules

  • All business logic must live inside the Handler's Handle() method.
  • Handlers receive dependencies via constructor injection only.
  • Handlers must inject IUnitOfWork (not AppDbContext directly).
  • Handlers must inject Core service interfaces (e.g., IPaymentGatewayService), never Infrastructure implementations.
  • Return types are always a DTO/Result record — never a raw Entity.

Controller Rules

// ✅ CORRECT — thin dispatcher
[HttpPost]
public async Task<IActionResult> Create([FromBody] CreateOrderCommand cmd, CancellationToken ct)
    => Ok(await _mediator.Send(cmd, ct));

// ❌ FORBIDDEN — logic in controller
[HttpPost]
public async Task<IActionResult> Create([FromBody] CreateOrderRequest req)
{
    var order = new Order { ... };  // ← business logic belongs in handler
    ...
}

3. MediatR Pipeline Behaviors

Two required behaviors must be registered in order in Application/DependencyInjection.cs:

  1. LoggingBehavior<TRequest, TResponse> — logs request type, execution time.
  2. ValidationBehavior<TRequest, TResponse> — runs FluentValidation; throws ValidationException before the handler is reached.
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));

RequestHandlerDelegate<TResponse> is parameterless in MediatR 12 — call as next(), not next(cancellationToken).


4. Mapping (Mapster)

  • All object transformations use IMapper.Adapt<TDestination>().
  • Mappings are configured in Application/Mapping/MappingConfig.cs using TypeAdapterConfig.
  • Handlers inject IMapper — never call TypeAdapter.Adapt<>() directly.

5. Modules (Microservice Readiness)

Applies when the backend is a modular monolith — one deployable, one database, a module per bounded context (a database schema plus the Features/* folders that own its tables). Within a module, code calls freely. Between modules: call a port in Core/Interfaces/<Module>/ or publish a MediatR notification — never send another module's command, load its entities, walk a navigation into its tables, or create a cycle.

Read reference/modular-monolith.md before any change that crosses a module boundary, adds a feature folder, or adds a port. Skip it for a single-module backend.


6. Security

  • All endpoints require [Authorize] by default. Opt-out with [AllowAnonymous] only for auth endpoints.
  • JWT claims are accessed exclusively via ICurrentUserService — never via HttpContext.User in handlers.
  • Brute-force protection (lockout) lives in the login handler — not in the controller or middleware.

Per-resource authorization — the handler's job, not the attribute's

[Authorize(Roles="...")] proves the caller has a role. It does not prove the caller owns the row whose id they just sent. Every handler that accepts an entity id from the request must verify ownership against ICurrentUserService.UserId before reading or writing:

// ❌ BOLA/IDOR — any authenticated caller can read any row by guessing/enumerating the id
var record = await _unitOfWork.Repository<Order>().GetByIdAsync(request.Id, ct);

// ✅ ownership is part of the lookup predicate
var record = await _unitOfWork.Repository<Order>().SingleOrDefaultAsync(
    b => b.Id == request.Id && b.OwnerUserId == _currentUser.UserId, ct)
    ?? throw new NotFoundException();

Rules:

  • Scope by owner in the query predicate, not with an if after loading — a post-load check that someone later refactors away fails open.
  • Return 404, not 403, for a resource the caller may not see. 403 confirms the row exists.
  • Each role's scope is its own data: a customer sees their own orders and payments, a manager the records of the organization they manage. Only Admin may cross that boundary, and an admin cross-account read writes an audit-log entry.
  • Never take userId, ownerId, or organizationId from the request body or query string as the identity to act on — derive it from ICurrentUserService. A request-supplied id is a target to authorize, never a claim of who you are.
  • Signed-link confirmation endpoints are [AllowAnonymous]: the token is the authorization. It must be single-use, expiring, high-entropy, and compared in constant time — and it authorizes exactly the one record it was minted for.
  • Never bind a request DTO straight onto an entity. Role, status, price, and eligibility fields must never be settable from the wire (over-posting → privilege escalation).

7. Error Handling

Throw project-owned exceptions (NotFoundException 404, ForbiddenException 403, ConflictException 409; FluentValidation ValidationException 422) and let a global handler map them to ProblemDetails. Never throw or map BCL types such as InvalidOperationException or KeyNotFoundException — the framework raises those for real defects, which must surface as a logged 500. No catch-all in handlers.

The full failure path — exception base and code vocabulary, handler implementation, wire shape, log levels, persistence and webhook failures — is [[error-handling-dotnet]].


Checklist Before Completing Work

  • Business logic lives in Application handlers, not controllers or Infrastructure
  • Layer dependencies point inward; Core has zero outward references
  • Command/query follows CQRS; controller only dispatches via MediatR
  • Handler injects IUnitOfWork and Core interfaces — not AppDbContext or Refit
  • Changes respect module boundaries: cross-module calls go through a Core port or an event, the accepted-coupling baseline did not grow, architecture tests green
  • A new feature folder is assigned a module; a new table lives in its module schema
  • Pipeline behaviors and Mapster conventions followed where applicable

Individual skills in this repo

This repo contains 4 individual skills — each has its own dedicated page.

Skills associés