C# / .NET Compendium PLEN
.NET / C# / CQRS, MediatR

CQRS - Command Query Responsibility Segregation

The fundamental idea

CQRS is an architectural pattern that says: operations that change state (Commands) should be separated from operations that only read data (Queries) - they are two different models, even if they operate on the same data.

// Command - ZMIENIA stan, zwykle nie zwraca danych (albo tylko Id/status)
public record CreateOrderCommand(string CustomerName, List<OrderItemDto> Items);

// Query - TYLKO CZYTA, nigdy nie zmienia stanu
public record GetOrderQuery(int OrderId);

Why this separation makes sense

Without CQRS - one service does everything, the data model for reads and writes is identical:

public class OrderService
{
    public async Task<Order> GetOrderAsync(int id) { /* ... */ }
    public async Task CreateOrderAsync(Order order) { /* ... */ }
    public async Task UpdateOrderStatusAsync(int id, string status) { /* ... */ }
}

This works well for simple CRUD applications, but starts to fail when: - Reads and writes have completely different performance requirements - a read (Query) often needs optimised, denormalised views (e.g. a sales report joining data from 5 tables), while a write (Command) needs full validation and business logic - The data model for display differs from the domain model - a list of orders in the UI needs a different "shape" of data than the Order entity used when processing the order - You want to scale reads and writes separately (e.g. more instances for reads, because there are more of them)

A Command - represents an intent to change

public record PlaceOrderCommand(string CustomerName, List<OrderItemDto> Items);

public class PlaceOrderHandler
{
    private readonly AppDbContext _context;

    public async Task<int> Handle(PlaceOrderCommand command)
    {
        var order = new Order { CustomerName = command.CustomerName };
        // logika biznesowa, walidacja, itd.
        _context.Orders.Add(order);
        await _context.SaveChangesAsync();
        return order.Id; // returns ONLY what is necessary (e.g. the Id of the new order)
    }
}

The rule: a Command shouldn't return large sets of data - that is not its role. It returns at most an Id, a success status, or nothing.

A Query - represents a request for data, WITHOUT side effects

public record GetOrderSummaryQuery(int OrderId);

public class GetOrderSummaryHandler
{
    private readonly AppDbContext _context;

    public async Task<OrderSummaryDto> Handle(GetOrderSummaryQuery query)
    {
        // This may be an optimised query, different from the one used with the Command
        return await _context.Orders
            .Where(o => o.Id == query.OrderId)
            .Select(o => new OrderSummaryDto(o.Id, o.CustomerName, o.Items.Count, o.TotalAmount))
            .FirstOrDefaultAsync();
    }
}

The rule: a Query never changes state - it must be completely safe to call many times (idempotent), with no side effects.

CQRS doesn't require separate databases - a common misconception

This is an important distinction frequently asked about in interviews: CQRS is a pattern at the level of code/application architecture - separating Command and Query as separate classes/models. You don't have to have a separate read database and a separate write database (that is an additional, optional technique, called CQRS with separate data stores, often combined with Event Sourcing) - in most business applications CQRS works on the same database, just with separated models/classes in the code.

Simple CQRS (the most common in practice):
Command → ta sama baza danych ← Query
(separated only in CODE - different classes, different models)

Advanced CQRS (rarer, for large scale):
Command → baza zapisu (write model)
              ↓ synchronizacja (np. przez event/message queue)
Query → osobna baza odczytu (read model, zdenormalizowana, zoptymalizowana pod konkretne zapytania)

The relation to the earlier conversation about Repository/UoW

This ties into the discussion about Repository - in a CQRS architecture the Command Handler often writes directly through DbContext (it needs the full domain model with business logic), while the Query Handler can write very simplified, optimised LINQ queries with a projection straight onto a DTO (Select(o => new OrderSummaryDto(...))), without going through full domain entities - this is where a "generic repository" (GetAllAsync() returning full entities) becomes particularly inconvenient, because it stifles the possibility of such optimisation.

Who calls the handlers? The missing link

A handler doesn't start by itself - it is an ordinary class with a Handle() method. It is called by the application's entry point (the presentation layer): an MVC controller / a Minimal API endpoint, a queue consumer (RabbitMQ, Kafka), a background task (BackgroundService, Hangfire) or a ViewModel in WPF/Blazor. The handler doesn't know and shouldn't know who calls it - thanks to this the same use case can be run from the API, from a queue and from a test.

Klient (HTTP) → Kontroler / Endpoint → Handler → DbContext → baza
                  (maps the request      (all the logic
                   na Command/Query)    use case'u)
                        ↑                    │
                        └──── wynik (Id / DTO) ┘

There are two ways for the entry point to get the right handler. Let's start with the one without any library, because it shows the whole mechanics.

Variant 1: the controller calls the handler directly (without MediatR)

Shared interfaces for handlers:

public interface ICommandHandler<in TCommand, TResult>
{
    Task<TResult> Handle(TCommand command, CancellationToken ct);
}

public interface IQueryHandler<in TQuery, TResult>
{
    Task<TResult> Handle(TQuery query, CancellationToken ct);
}

// Handlers implement the interfaces
public class PlaceOrderHandler : ICommandHandler<PlaceOrderCommand, int>
{
    private readonly AppDbContext _context;
    public PlaceOrderHandler(AppDbContext context) => _context = context;

    public async Task<int> Handle(PlaceOrderCommand command, CancellationToken ct)
    {
        var order = new Order { CustomerName = command.CustomerName };
        _context.Orders.Add(order);
        await _context.SaveChangesAsync(ct);
        return order.Id;
    }
}

public class GetOrderSummaryHandler : IQueryHandler<GetOrderSummaryQuery, OrderSummaryDto?>
{
    private readonly AppDbContext _context;
    public GetOrderSummaryHandler(AppDbContext context) => _context = context;

    public Task<OrderSummaryDto?> Handle(GetOrderSummaryQuery query, CancellationToken ct) =>
        _context.Orders
            .Where(o => o.Id == query.OrderId)
            .Select(o => new OrderSummaryDto(o.Id, o.CustomerName, o.Items.Count, o.TotalAmount))
            .FirstOrDefaultAsync(ct);
}

Registration in DI (Program.cs) - each handler as Scoped, because it uses DbContext:

builder.Services.AddScoped<ICommandHandler<PlaceOrderCommand, int>, PlaceOrderHandler>();
builder.Services.AddScoped<IQueryHandler<GetOrderSummaryQuery, OrderSummaryDto?>, GetOrderSummaryHandler>();

And it is precisely the controller that calls the handlers - it gets them through the constructor (DI) and translates the HTTP request into a Command/Query:

[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
    private readonly ICommandHandler<PlaceOrderCommand, int> _placeOrder;
    private readonly IQueryHandler<GetOrderSummaryQuery, OrderSummaryDto?> _getOrder;

    public OrdersController(
        ICommandHandler<PlaceOrderCommand, int> placeOrder,
        IQueryHandler<GetOrderSummaryQuery, OrderSummaryDto?> getOrder)
    {
        _placeOrder = placeOrder;
        _getOrder = getOrder;
    }

    [HttpPost]
    public async Task<IActionResult> Create(PlaceOrderRequest request, CancellationToken ct)
    {
        // 1. kontroler tylko mapuje request HTTP na Command
        var command = new PlaceOrderCommand(request.CustomerName, request.Items);

        // 2. calls the handler and gets the result (the Id)
        var orderId = await _placeOrder.Handle(command, ct);

        // 3. turns the result into an HTTP response
        return CreatedAtAction(nameof(Get), new { id = orderId }, orderId);
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> Get(int id, CancellationToken ct)
    {
        var dto = await _getOrder.Handle(new GetOrderSummaryQuery(id), ct);
        return dto is null ? NotFound() : Ok(dto);
    }
}

In Minimal API it is the same, only the handler arrives as an endpoint parameter (DI injects it automatically):

app.MapPost("/api/orders", async (
    PlaceOrderRequest request,
    ICommandHandler<PlaceOrderCommand, int> handler,
    CancellationToken ct) =>
{
    var id = await handler.Handle(new PlaceOrderCommand(request.CustomerName, request.Items), ct);
    return Results.Created($"/api/orders/{id}", id);
});

The plus of this variant: zero "magic" - in the IDE you go from the controller straight to the handler (F12). The minus: a controller with many actions gets a long list of handlers in the constructor ("constructor bloat"), and every new handler has to be registered in DI by hand (this can be automated by scanning the assembly, e.g. with the Scrutor library).

Variant 2: the controller calls a mediator, and the mediator calls the handler

To avoid a long list of dependencies, an intermediary (a Mediator / dispatcher) is introduced. The controller knows only it and sends it the Command/Query, and the intermediary itself finds the right handler in DI by the type of the message. A ready implementation is MediatR - the full description and an example controller with IMediator are in the topic MediatR - how it works and how to use it:

// The controller: one dependency instead of N handlers
var orderId = await _mediator.Send(new PlaceOrderCommand(request.CustomerName, request.Items));
//                 ↑ MediatR finds PlaceOrderHandler in DI and calls its Handle()

An additional benefit: since everything passes through one point, you can attach validation, logging and transactions there (Pipeline Behaviors).

The full flow - what exactly happens

  1. The client sends POST /api/orders with JSON.
  2. ASP.NET Core performs model binding and creates the controller (DI injects the handler or IMediator).
  3. The controller builds a PlaceOrderCommand and calls the handler (directly or through the mediator).
  4. The handler carries out the use case: business rules, saving through DbContext, SaveChangesAsync.
  5. The handler returns the Id; the controller turns it into 201 Created.
  6. With a GET the same scheme, but with a Query Handler that only reads and returns a DTO.

Who else can call handlers

  • A queue consumer - a message from RabbitMQ/Kafka is turned into a Command and goes to the same handler the API uses.
  • A background task (BackgroundService, Hangfire) - e.g. a nightly recalculation Command. Remember to create a DI scope (IServiceScopeFactory), because the handler is Scoped.
  • A unit / integration test - creates the handler and calls Handle() without HTTP.
  • Another handler - technically possible, but usually a smell; instead use domain events or extract the shared logic into a domain service.

Rules worth remembering

  • The controller is thin - it maps the request to a Command/Query, calls the handler, maps the result to a response. No business logic.
  • A Query Handler never calls a Command Handler and doesn't change state.
  • One handler = one use case; a handler doesn't know HTTP (HttpContext, IActionResult) - which is why it works from any entry point.
  • The Command/Query separation concerns the code, not the transport: both can go through the same HTTP endpoint and the same database.

The advantages of CQRS

  • Clarity of intent - looking at PlaceOrderCommand, you know exactly what this operation does, without reading the implementation
  • The ability to optimise reads and writes independently
  • Easier testing - Commands/Queries are simple, immutable data objects (a great example for record, which we talked about!) with one Handler to test
  • Scalability - in more complex systems, reads and writes can be scaled independently

The drawbacks/costs of CQRS

  • More code for simple CRUD operations - for a trivial "add/edit/delete" application without complex business logic, CQRS may be overkill
  • Potential duplication of models (the Command DTO, Query DTO and domain entity may look similar, but are separate types)

When to use CQRS - a practical rule

CQRS makes sense when the write logic (validation, business rules, domain effects) is significantly different from the read logic (reporting, display, search) - typically in larger, complex business systems. For simple CRUDs (a small internal admin panel) a classic service with one class is often enough, without the overhead of extra structure.

Buy me a coffee