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

CQRS with MediatR - the mechanics of the implementation

MediatR - a library implementing the Mediator pattern

MediatR is a popular .NET library implementing the Mediator pattern - an intermediary through which all Commands/Queries pass, instead of calling Handlers directly.

// Definicja Command - implementuje IRequest<TResponse> z MediatR
public record PlaceOrderCommand(string CustomerName, List<OrderItemDto> Items) : IRequest<int>;

// Definicja Query
public record GetOrderQuery(int OrderId) : IRequest<OrderDto>;

A Handler - implements the logic for a specific Command/Query

public class PlaceOrderHandler : IRequestHandler<PlaceOrderCommand, int>
{
    private readonly AppDbContext _context;

    public PlaceOrderHandler(AppDbContext context) => _context = context;

    public async Task<int> Handle(PlaceOrderCommand request, CancellationToken cancellationToken)
    {
        var order = new Order { CustomerName = request.CustomerName };
        foreach (var item in request.Items)
        {
            order.Items.Add(new OrderItem { ProductId = item.ProductId, Quantity = item.Quantity });
        }

        _context.Orders.Add(order);
        await _context.SaveChangesAsync(cancellationToken);

        return order.Id;
    }
}

The key rule: one Handler per Command/Query - this is a 1:1 mapping, unlike a traditional service, which could have many methods. This supports the Single Responsibility Principle (from SOLID) at the level of the operation, not just the class.

The controller - sends through IMediator, doesn't call a service directly

[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
    private readonly IMediator _mediator; // the ONLY dependency - no need to inject 10 services!

    public OrdersController(IMediator mediator) => _mediator = mediator;

    [HttpPost]
    public async Task<ActionResult<int>> CreateOrder(PlaceOrderCommand command)
    {
        var orderId = await _mediator.Send(command); // MediatR finds the appropriate Handler and calls it
        return CreatedAtAction(nameof(GetOrder), new { id = orderId }, orderId);
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<OrderDto>> GetOrder(int id)
    {
        var order = await _mediator.Send(new GetOrderQuery(id));
        return order == null ? NotFound() : Ok(order);
    }
}

This is a significant architectural change - the Controller doesn't have an IOrderService with dozens of methods injected. It has only IMediator, and MediatR automatically finds the right Handler based on the type of the passed Command/Query.

How MediatR "knows" which Handler to call - the mechanics

// Rejestracja w DI (Program.cs)
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Program).Assembly));

At startup MediatR scans the assembly, finds all classes implementing IRequestHandler<TRequest, TResponse>, and automatically registers them in the DI container. When you call _mediator.Send(command):

// Roughly, what happens "under the hood" in MediatR:
public async Task<TResponse> Send<TResponse>(IRequest<TResponse> request)
{
    var requestType = request.GetType(); // np. typeof(PlaceOrderCommand)
    var handlerType = typeof(IRequestHandler<,>).MakeGenericType(requestType, typeof(TResponse));

    var handler = _serviceProvider.GetRequiredService(handlerType); // resolved from the DI container

    return await ((dynamic)handler).Handle((dynamic)request, cancellationToken);
}

This is essentially a generic Service Locator, but closed to just Commands/Queries, in a controlled way (unlike the Service Locator anti-pattern we discussed with the ways of doing DI, here the type→handler mapping is explicit and checked at compile time by the IRequestHandler<TRequest, TResponse> type system).

Pipeline Behaviors - middleware for Commands/Queries (a very practical feature)

This is one of MediatR's most valuable features - the ability to add cross-cutting logic (cross-cutting concerns) that runs for ALL (or selected) Commands/Queries, without duplicating code in every Handler:

public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    private readonly IValidator<TRequest> _validator;

    public async Task<TResponse> Handle(
        TRequest request,
        RequestHandlerDelegate<TResponse> next, // the "continuation" - the next step in the chain
        CancellationToken cancellationToken)
    {
        var validationResult = await _validator.ValidateAsync(request);
        if (!validationResult.IsValid)
            throw new ValidationException(validationResult.Errors);

        return await next(); // passing on to the actual Handler (or the next behavior)
    }
}
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
    private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;

    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken ct)
    {
        _logger.LogInformation($"Przetwarzanie {typeof(TRequest).Name}");
        var response = await next();
        _logger.LogInformation($"Finished {typeof(TRequest).Name}");
        return response;
    }
}
// Registration - the order matters, it creates a "chain"
builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));

This is exactly the same IoC mechanism ("your code is called by the framework, in a chain with next()") that we discussed with ASP.NET Core middleware - Pipeline Behaviors in MediatR are middleware, but at the level of Commands/Queries, not HTTP requests.

Practical uses of Pipeline Behaviors: - Validation (as above, often with the FluentValidation library) - Logging every operation - Transactions (wrapping Handle() in BeginTransactionAsync/CommitAsync) - Caching Query results - Measuring execution time (performance monitoring)

FluentValidation + MediatR - a typical combination

public class PlaceOrderCommandValidator : AbstractValidator<PlaceOrderCommand>
{
    public PlaceOrderCommandValidator()
    {
        RuleFor(x => x.CustomerName).NotEmpty().MaximumLength(100);
        RuleFor(x => x.Items).NotEmpty().WithMessage("An order must have at least one item");
    }
}

A Handler doesn't need to contain manual validation - the ValidationBehavior (the Pipeline Behavior above) automatically performs it before calling Handle() of every Command/Query for which a matching validator exists.

The advantages of such an architecture

  • The controller is very cheap - one dependency (IMediator), instead of a growing list of services injected through the constructor (back to the "constructor bloat" we discussed with DI)
  • Cross-cutting logic in one place (Pipeline Behaviors) - you don't have to remember to add logging/validation in every new Handler
  • Testing a Handler in isolation - a Handler is a simple class with one Handle() method, easy to test without mocking a controller or HTTP

The drawbacks/costs

  • "Magic" that makes the flow harder to follow - to understand what happens on _mediator.Send(command), you have to know about MediatR and the Handler registration mechanism - it is not as explicit as a direct call of a service method (_orderService.CreateOrder(...))
  • More files/classes for simple operations (a Command + Handler + Validator for something that could be one service method)

Summary

MediatR implements CQRS through the Mediator pattern - Commands/Queries are simple, immutable objects (a good use of record, which we talked about), a Handler implements the logic for one specific request type, and Pipeline Behaviors add cross-cutting logic (validation, logging, transactions) without duplicating code in every Handler. The controller becomes very "cheap" - it needs only IMediator, and the framework takes care of the rest through the mechanism of registering and resolving Handlers from the DI container.

Buy me a coffee