Skip to main content

Lesson 3 of 8

Full MediatR CQRS - Request Pipeline

MediatR dispatches Commands and Queries through a pipeline of behaviors. This orders cross-cutting concerns cleanly: every command is validated before the handler runs, every request is logged with timing, and domain events are dispatched after commit - all transparent to the handler.

30 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

MediatR Pipeline Behaviors

MediatR Pipeline Behaviors
using MediatR;

// ━━ 1. Logging behavior - wraps ALL requests ━━
public class LoggingBehavior2<TRequest, TResponse>(ILogger<LoggingBehavior2<TRequest, TResponse>> logger)
    : IPipelineBehavior<TRequest, TResponse>
    where TRequest : notnull
{
    public async Task<TResponse> Handle(
        TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken ct)
    {
        var requestName = typeof(TRequest).Name;
        logger.LogInformation("Handling {RequestName}: {@Request}", requestName, request);

        var sw = System.Diagnostics.Stopwatch.StartNew();
        try
        {
            var response = await next();
            logger.LogInformation("{RequestName} handled in {ElapsedMs}ms", requestName, sw.ElapsedMilliseconds);
            return response;
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "{RequestName} failed after {ElapsedMs}ms", requestName, sw.ElapsedMilliseconds);
            throw;
        }
    }
}

// ━━ 2. Validation behavior - before every command ━━
public class ValidationBehavior2<TRequest, TResponse>(IEnumerable<IValidator<TRequest>> validators)
    : IPipelineBehavior<TRequest, TResponse>
    where TRequest : notnull
{
    public async Task<TResponse> Handle(
        TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken ct)
    {
        if (!validators.Any()) return await next();

        var errors = (await Task.WhenAll(
                validators.Select(v => v.ValidateAsync(request, ct))))
            .SelectMany(r => r.Errors)
            .Where(f => f is not null)
            .ToList();

        if (errors.Count > 0) throw new FluentValidation.ValidationException(errors);

        return await next();
    }
}

// ━━ 3. Domain event dispatcher - after handler commits ━━
public class DomainEventBehavior<TRequest, TResponse>(
    AppDbContext db, IMediator mediator)
    : IPipelineBehavior<TRequest, TResponse>
    where TRequest : notnull
{
    public async Task<TResponse> Handle(
        TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken ct)
    {
        var response = await next(); // handler runs + SaveChanges called

        // Dispatch all domain events raised by aggregates
        var aggregates = db.ChangeTracker.Entries<IAggregateRoot>()
            .Select(e => e.Entity)
            .Where(e => e.Events.Any())
            .ToList();

        var events = aggregates.SelectMany(a => a.Events).ToList();
        aggregates.ForEach(a => a.ClearEvents());

        foreach (var domainEvent in events)
            await mediator.Publish(domainEvent, ct);

        return response;
    }
}

// ━━ Place Order command + handler ━━
public record PlaceOrderCommand2(Guid CustomerId, List<OrderLine> Lines)
    : IRequest<Result<OrderSummary>>;

public record OrderLine(Guid ProductId, int Quantity, decimal UnitPrice, string Currency);

public class PlaceOrderCommandHandler(IOrderRepository orders, IProductRepository products, AppDbContext db)
    : IRequestHandler<PlaceOrderCommand2, Result<OrderSummary>>
{
    public async Task<Result<OrderSummary>> Handle(PlaceOrderCommand2 cmd, CancellationToken ct)
    {
        var order = Order.Create(cmd.CustomerId);

        foreach (var line in cmd.Lines)
        {
            var product = await products.GetByIdAsync(line.ProductId, ct);
            if (product is null) return Result<OrderSummary>.NotFound("Product", line.ProductId);

            order.AddItem(line.ProductId, Money.Of(line.UnitPrice, line.Currency), line.Quantity);
        }

        order.Place(); // raises OrderPlacedEvent
        orders.Add(order);
        await db.SaveChangesAsync(ct); // DomainEventBehavior dispatches events after this

        return Result<OrderSummary>.Success(new OrderSummary(order.Id, order.Status.ToString(), order.Total.ToString()));
    }
}

// Query handler - read-optimized, no entity tracking
public record GetOrderQuery(Guid OrderId) : IRequest<OrderSummary?>;

public class GetOrderHandler(IReadDbContext readDb) : IRequestHandler<GetOrderQuery, OrderSummary?>
{
    public async Task<OrderSummary?> Handle(GetOrderQuery query, CancellationToken ct) =>
        await readDb.Orders
            .Where(o => o.Id == query.OrderId)
            .Select(o => new OrderSummary(o.Id, o.Status, o.Total.ToString()))
            .FirstOrDefaultAsync(ct);
}

// Placeholder types
record Result<T>(bool IsSuccess, T? Value = default, string? Error = null)
{
    public static Result<T> Success(T v) => new(true, v);
    public static Result<T> NotFound(string r, object id) => new(false, Error: $"{r} {id} not found");
}
record OrderSummary(Guid Id, string Status, string Total);
interface IOrderRepository { void Add(Order o); }
interface IProductRepository { Task<object?> GetByIdAsync(Guid id, CancellationToken ct); }
interface IReadDbContext { IQueryable<OrderReadModel> Orders { get; } }
class OrderReadModel { public Guid Id { get; set; } public string Status { get; set; } = ""; public Money Total { get; set; } = Money.Zero("USD"); }
class AppDbContext { public Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker ChangeTracker { get; } = null!; public Task<int> SaveChangesAsync(CancellationToken ct) => Task.FromResult(0); }
interface IValidator<T> { Task<FluentValidation.Results.ValidationResult> ValidateAsync(T v, CancellationToken ct); }

Tip

Tip

Practice Full MediatR CQRS Request Pipeline in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Full MediatR CQRS Request Pipeline from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Full MediatR CQRS Request Pipeline is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done