What is the Mediator pattern (and MediatR)?

SOLID & Design Patterns Patterns Intermediate 3–5 Yrs5+ Yrs Architecture 1 min read

Quick Answer

Mediator routes messages between components so they don't reference each other directly — they only know the mediator. In .NET, MediatR is a popular library that implements a request/handler pipeline: a controller sends a CreateOrderCommand, and MediatR finds and invokes the matching IRequestHandler, with optional cross-cutting pipeline behaviours (validation, logging, transactions).

Mediator means components talk through a central object instead of holding references to each other. In .NET that's usually MediatR: my controller builds a command object and calls _mediator.Send, and MediatR dispatches it to the one handler that handles that command type. The wins are thin controllers, one handler per use case which lines up with Single Responsibility, and pipeline behaviours — a single place to plug in validation, logging or a transaction that wraps every request. The pushback is that it adds indirection and makes the call graph harder to follow, so in a small service I might just inject the handler directly.

What it buys you: thin controllers (one line: await _mediator.Send(command)), one handler per use case (SRP), and a clean place for cross-cutting concerns via behaviours that wrap every request.

Criticisms: it can hide the call graph (“go to definition” lands on an interface), it's indirection for its own sake in small apps, and some argue injecting the handler directly is simpler. It pairs naturally with lightweight CQRS.