xiaohongshu
xiaohongshu
cqrs-mediatr-guidelines
CQRS (Command Query Responsibility Segregation) patterns with MediatR for .NET Clean Architecture projects. Covers commands, queries, handlers, validation, and pipeline behaviors.
Full skill instructions
Project-Agnostic CQRS Guidelines
Placeholders use
{Placeholder}syntax - see docs/TEMPLATE_GLOSSARY.md.
Provides best practices for implementing CQRS (Command Query Responsibility Segregation) using MediatR in .NET Clean Architecture projects. Ensures consistent, testable, and maintainable application logic.
Triggered by:
**/*Command.cs, **/*Query.cs, **/*Handler.cs, **/*Validator.csIRequest, IRequestHandler, AbstractValidatorgraph TD
subgraph Presentation Layer
Controller -- "Sends IRequest" --> MediatR[MediatR]
end
subgraph Application Layer
MediatR --> Handler[Handler]
Handler --> Validator[Validator]
Handler --> Mapper[AutoMapper]
Handler --> Repository[Repository]
Repository --> Domain[Domain Entities]
end
subgraph Infrastructure Layer
Repository --> DB[Database]
end
style MediatR fill:#fbe5c5,stroke:#333
style Handler fill:#e5c5fb,stroke:#333
style Validator fill:#e5fbe5,stroke:#333
style Mapper fill:#fbe5e5,stroke:#333
style Repository fill:#c5fbe5,stroke:#333
style Domain fill:#c5fbc5,stroke:#333
style DB fill:#c5c5fb,stroke:#333
CancellationToken to all asynchronous methods to enable cancellation.For more detailed examples, refer to the resources/ folder within this skill.
| Resource | Description |
|---|---|
| command-patterns.md | Command structure, naming, handlers |
| query-patterns.md | Query structure, pagination, projections |
| handler-patterns.md | Handler implementation, DI, error handling |
| validation-integration.md | FluentValidation patterns and manual integration |
| complete-examples.md | End-to-end feature examples for CQRS |
Commands represent actions that modify the application's state.
// File: {Project}.Application/Features/{Entities}/Requests/Commands/Create{Entity}Command.cs
namespace {Project}.Application.Features.{Entities}.Requests.Commands;
using MediatR;
using {Project}.Application.DTOs.{Entity};
using {Project}.Application.Responses;
public class Create{Entity}Command : IRequest<BaseCommandResponse<{IdType}>>
{
public Create{Entity}Dto {Entity}Dto { get; set; } = null!; // Command wraps a DTO
}
For more details, see command-patterns.md.
Queries represent requests for data and should not alter the application's state.
// File: {Project}.Application/Features/{Entities}/Requests/Queries/Get{Entity}ListRequest.cs
namespace {Project}.Application.Features.{Entities}.Requests.Queries;
using System.Collections.Generic;
using {Project}.Application.DTOs.{Entity};
using MediatR;
public class Get{Entity}ListRequest : IRequest<List<{Entity}ListDto>>
{
// Can include filter properties if needed
}
For more details, see query-patterns.md.
Handlers contain the business logic to execute a command or query.
// File: {Project}.Application/Features/{Entities}/Handlers/Commands/Create{Entity}CommandHandler.cs
namespace {Project}.Application.Features.{Entities}.Handlers.Commands;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using {Project}.Application.Contracts.Persistence;
using {Project}.Application.DTOs.{Entity}.Validators;
using {Project}.Application.Features.{Entities}.Requests.Commands;
using {Project}.Application.Responses;
using MediatR;
public class Create{Entity}CommandHandler : IRequestHandler<Create{Entity}Command, BaseCommandResponse<{IdType}>>
{
private readonly I{Entity}Repository _{entity}Repository;
private readonly IMapper _mapper;
// ... other dependencies needed for validation or business logic
public Create{Entity}CommandHandler(I{Entity}Repository {entity}Repository, IMapper mapper /* ... */)
{
_{entity}Repository = {entity}Repository;
_mapper = mapper;
}
public async Task<BaseCommandResponse<{IdType}>> Handle(Create{Entity}Command request, CancellationToken cancellationToken)
{
var response = new BaseCommandResponse<{IdType}>();
// ✅ CRITICAL: Manual validator instantiation with dependencies
var validator = new Create{Entity}DtoValidator(/* repositories */);
var validationResult = await validator.ValidateAsync(request.{Entity}Dto, cancellationToken);
if (!validationResult.IsValid)
{
response.Success = false;
response.Message = "{Entity} creation failed.";
response.Errors = validationResult.Errors.Select(e => e.ErrorMessage).ToList();
return response;
}
var {entity} = _mapper.Map<{Entity}>(request.{Entity}Dto);
{entity}.ViewCount = 0; // Set properties not coming from DTO
{entity} = await _{entity}Repository.Create({entity});
response.Success = true;
response.Id = {entity}.Id;
response.Message = "{Entity} created successfully.";
return response;
}
}
For more details, see handler-patterns.md.
FluentValidation is used for input validation, with validators instantiated manually within handlers.
// File: {Project}.Application/DTOs/{Entity}/Validators/Create{Entity}DtoValidator.cs
namespace {Project}.Application.DTOs.{Entity}.Validators;
using FluentValidation;
using {Project}.Application.Contracts.Persistence;
public class Create{Entity}DtoValidator : AbstractValidator<Create{Entity}Dto>
{
public Create{Entity}DtoValidator(I{RelatedEntity1}Repository {relatedEntity1}Repository /* ... */)
{
// ... inject repositories needed for FK validation
RuleFor(x => x.Title)
.NotEmpty().WithMessage("Title is required")
.MaximumLength(200);
RuleFor(x => x.{RelatedEntity1}Id)
.NotEmpty().WithMessage("{RelatedEntity1} is required")
.MustAsync(async (id, cancellation) => await {relatedEntity1}Repository.Exists(id))
.WithMessage("{RelatedEntity1} not found");
}
}
For more details, see validation-integration.md.
CancellationToken to all asynchronous methods.BaseCommandResponse<{IdType}> for command responses (except bool for Delete).IRequest without a response type..Result or .Wait() in asynchronous code.BaseCommandResponse.Related Documentation:
docs/ARCHITECTURE.md - Overall system architecture.clean-architecture-rules - Dependency enforcement.xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience