Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 7 · Lesson 63 · 7 min read

CQRS and MediatR in .NET Without the Hype

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A Tiny Mediator, Decorators and an Authorization Rule That Cannot Be Forgotten
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Explain command query responsibility segregation at the level a typical API needs, structure handlers with a small hand-rolled or library-based mediator, build pipeline behaviors for validation and authorization, and make authorization mandatory so that a forgotten check becomes a build or test failure.

Concept Explanation

Command Query Responsibility Segregation is a simple idea wrapped in an intimidating name. Operations that change state, commands, and operations that read state, queries, are modeled separately, because they have different needs. Commands must enforce rules, run in transactions, and return little. Queries must be fast, shaped for a screen, and have no side effects. Bertrand Meyer's command-query separation principle from the 1980s applied this to methods, and Greg Young extended it to whole models around 2010. At its simplest, CQRS just means that a write path with domain objects and a read path with direct projections into DTOs, exactly what you did on Days 23 and 35, are different code.

You can go much further, with separate databases for reads and writes and event sourcing, and some systems need that, as Phase 10 will touch on. Most APIs need none of it. The valuable, low-cost version is one class per use case: a command or query type carrying the input, a handler that does the work, and a uniform way to invoke it. That is the mediator pattern: the caller sends a request object to a mediator, which finds the right handler. Its main benefit is not the indirection itself but that every use case flows through one pipeline, where cross-cutting behaviors can wrap it: validation, authorization, logging, transactions, and caching.

The popular library MediatR implements this but moved to a commercial license in 2025, so many teams now choose alternatives such as Wolverine, the source-generated Mediator library, or a few dozen lines of their own code. A hand-rolled version is genuinely small: an interface for handlers, a way to resolve them from the dependency injection container, and decorators implementing the same interface to add behaviors. Decorators are plain classes that wrap a handler, so nothing magical is involved, and the container composes them in a fixed order. Beware of the common overuse: sending trivial calls through a mediator adds indirection that makes code harder to follow, and a controller that only forwards to a handler adds nothing. Use it where the pipeline pays for itself.

The pipeline is where security becomes systematic. An authorization behavior can require that every command and query declare how it is authorized, either by implementing an interface that states the required policy or by being explicitly marked as public. A request that does neither fails at startup or in a test, turning the classic mistake of forgetting the check into something that cannot be shipped. A validation behavior runs the FluentValidation validators for the request before the handler sees it. An audit behavior records who invoked which command. The ordering matters: authorization runs before validation, so unauthorized callers do not learn anything about what would have been accepted.

ElementRoleNote
CommandRequest that changes stateReturns an id or a result, not data for a screen
QueryRequest that reads stateNo side effects, projected straight to DTOs
HandlerOne class per use caseContains the logic, easy to test
MediatorRoutes a request to its handlerLibrary or a small hand-rolled class
Pipeline behavior or decoratorWraps every handlerAuthorization, validation, logging, transactions
Mandatory authorizationEvery request declares its policyA forgotten check fails a test, not production

Worked Example: A Tiny Mediator, Decorators and an Authorization Rule That Cannot Be Forgotten

The interfaces and decorators below are the whole mechanism. The last test scans the assembly and fails if any request has no authorization declaration.

C#
public interface IRequest<TResponse>;
public interface IHandler<TRequest, TResponse> where TRequest : IRequest<TResponse>
{
    Task<TResponse> HandleAsync(TRequest request, CancellationToken ct);
}

// Every request must say who may send it: a policy name, or explicitly public.
public interface IAuthorizedRequest { string Policy { get; } }
public interface IPublicRequest;

public sealed class Sender(IServiceProvider services)
{
    public Task<TResponse> SendAsync<TResponse>(IRequest<TResponse> request, CancellationToken ct)
    {
        var handlerType = typeof(IHandler<,>).MakeGenericType(request.GetType(), typeof(TResponse));
        dynamic handler = services.GetRequiredService(handlerType);
        return handler.HandleAsync((dynamic)request, ct);
    }
}

// Decorator 1: authorization, outermost, so unauthorized callers learn nothing else.
public sealed class AuthorizationDecorator<TRequest, TResponse>(
    IHandler<TRequest, TResponse> inner, IAuthorizationService auth, ICurrentUser user)
    : IHandler<TRequest, TResponse> where TRequest : IRequest<TResponse>
{
    public async Task<TResponse> HandleAsync(TRequest request, CancellationToken ct)
    {
        if (request is IAuthorizedRequest ar)
        {
            var result = await auth.AuthorizeAsync(user.Principal, ar.Policy);
            if (!result.Succeeded) throw new ForbiddenException();
        }
        else if (request is not IPublicRequest)
            throw new InvalidOperationException($"{typeof(TRequest).Name} declares no authorization.");   // deny by default

        return await inner.HandleAsync(request, ct);
    }
}

// Decorator 2: validation with FluentValidation, inside authorization.
public sealed class ValidationDecorator<TRequest, TResponse>(
    IHandler<TRequest, TResponse> inner, IEnumerable<IValidator<TRequest>> validators)
    : IHandler<TRequest, TResponse> where TRequest : IRequest<TResponse>
{
    public async Task<TResponse> HandleAsync(TRequest request, CancellationToken ct)
    {
        var failures = (await Task.WhenAll(validators.Select(v => v.ValidateAsync(request, ct))))
            .SelectMany(r => r.Errors).ToList();
        if (failures.Count > 0) throw new ValidationException(failures);
        return await inner.HandleAsync(request, ct);
    }
}

// Registration with Scrutor: decorate every handler, order = outermost last.
services.Scan(s => s.FromAssemblyOf<Program>().AddClasses(c => c.AssignableTo(typeof(IHandler<,>)))
    .AsImplementedInterfaces().WithScopedLifetime());
services.Decorate(typeof(IHandler<,>), typeof(ValidationDecorator<,>));
services.Decorate(typeof(IHandler<,>), typeof(AuthorizationDecorator<,>));   // wraps validation
C#
// A command and its handler: one use case, one file.
public sealed record InviteMember(Guid ProjectId, string Email, ProjectRole Role)
    : IRequest<Guid>, IAuthorizedRequest { public string Policy => "ProjectAdmin"; }

public sealed class InviteMemberHandler(AppDb db, IInvitationTokens tokens, IEmailSender email)
    : IHandler<InviteMember, Guid>
{
    public async Task<Guid> HandleAsync(InviteMember cmd, CancellationToken ct) { /* ... */ return Guid.Empty; }
}

// A read stays a plain query projected to a DTO. No domain objects, no ceremony.
public sealed record ListProjects : IRequest<IReadOnlyList<ProjectSummary>>, IAuthorizedRequest { public string Policy => "SignedIn"; }
Java
// The safety net: a request type that forgets authorization fails the build.
[Fact]
public void Every_request_declares_authorization()
{
    var offenders = typeof(InviteMember).Assembly.GetTypes()
        .Where(t => t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IRequest<>)))
        .Where(t => !typeof(IAuthorizedRequest).IsAssignableFrom(t) && !typeof(IPublicRequest).IsAssignableFrom(t))
        .Select(t => t.Name).ToList();
    Assert.Empty(offenders);
}

Resource-based checks such as membership of a specific project still happen inside the handler through the query filters and handlers of Day 47, because they need the loaded data. The decorator handles the coarse policy for every request uniformly, and the test guarantees nobody skips it.

A command or query passes an authorization decorator first, then validation, then its single-purpose handler. Requests must declare a policy or be explicitly public, and an assembly test fails the build if one does not.
A command or query passes an authorization decorator first, then validation, then its single-purpose handler. Requests must declare a policy or be explicitly public, and an assembly test fails the build if one does not.

Real-World Examples

  • Greg Young popularized CQRS around 2010 as an extension of Bertrand Meyer's command-query separation from his 1988 book Object-Oriented Software Construction. Young has repeatedly warned that CQRS is a pattern to apply to specific parts of a system that benefit from it, not a top-level architecture, which matches the advice to keep it lightweight for typical APIs.
  • In 2025 the maintainers of MediatR and AutoMapper announced a move to commercial licensing under a new company, which prompted many .NET teams to evaluate free alternatives or hand-rolled handlers. The episode is a reminder that a pattern is more durable than any library, and that keeping the mechanism small and behind your own interfaces keeps the choice reversible.
Key TakeawaysCQRS at its useful minimum is one handler class per use case in your application, with separate paths for writes and for reads. Handlers are invoked through a small mediator that lets decorators wrap every handler. Build validation and authorization behaviors once, order authorization first, make every request declare its policy or be explicitly public, and prove it with a test so a forgotten check cannot ship.

Review Questions & Answers

Treat commands and queries as separate use cases with their own handlers: commands go through domain objects and rules, while queries project directly into DTOs with no side effects. There is no need for separate databases or event sourcing. The gain is that each path is optimized for its purpose and cross-cutting behavior can wrap them uniformly.

If validation ran first, an unauthorized caller would receive detailed validation feedback and learn about the shape of the operation before being refused. Running authorization outermost ensures unauthorized requests are rejected before anything else happens, so they learn nothing and consume minimal resources.

It turns a silent omission into a visible failure. A new command that neither states a policy nor is explicitly marked public is rejected at runtime and caught by the assembly-scanning test, so a forgotten check cannot reach production unnoticed. Public access becomes a deliberate, reviewable decision.

When it merely forwards a call with no cross-cutting behavior to apply, since the extra indirection makes code harder to navigate without adding value. It pays off when many use cases share a pipeline of concerns like authorization, validation, and auditing, and when handlers benefit from being small, single-purpose classes.