C# › Design Patterns in C#
How would you implement the CQRS (Command Query Responsibility Segregation) pattern's basic structure in a C# application using MediatR-style handlers?
AdvancedAnswer
CQRS separates WRITE operations (Commands, which change state and typically return little/nothing) from READ operations (Queries, which return data without side effects) into distinct request/handler pairs — often implemented with a mediator pattern where each Command/Query has its own dedicated Handler class, keeping business logic focused and independently testable.
public record CreateOrderCommand(int CustomerId, List<OrderItem> Items) : IRequest<int>;
public class CreateOrderHandler : IRequestHandler<CreateOrderCommand, int> {
public async Task<int> Handle(CreateOrderCommand command, CancellationToken ct) {
var order = new Order(command.CustomerId, command.Items);
await _repository.AddAsync(order);
return order.Id;
}
}Real-world example Structuring a complex domain's write and read operations into clearly separated, independently-scalable handler classes.