Advertisement
Advanced 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?

Short answer

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…

Save C# mock interview
Advertisement
AModel answer
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.
Likely follow-ups
  • What benefits does CQRS provide specifically in systems with very different read versus write scaling requirements?
Related topics