You don't need MediatR, but you do need decorators
A team decides to stop using MediatR. The pull request is a pleasure to review: the package is gone, every endpoint asks for its handler and calls it, and the diff is mostly red. Sixty handlers, all tests green, three approvals.
Three weeks later there is an order for -5 widgets in the database, and the warehouse system shows five more widgets than anyone ever delivered.
Nobody deleted the validation. It was never in the handler. It ran around the handler, and the thing that ran it was removed.
This article shows what MediatR actually does for you, which half you can drop without loss, and how to keep the other half in about sixty lines with nothing but the built-in container. Examples use ASP.NET Core, EF Core and PostgreSQL, but the reasoning holds for any stack with a mediator library and a dependency injection container.
The whole argument in 40 seconds.
The version everyone writes first
With MediatR, an endpoint sends a request and something, somewhere, handles it:
app.MapPost("/orders", async (PlaceOrderBody body, ISender sender, CancellationToken ct) =>
Created(await sender.Send(ToCommand(body), ct)));
Without it, the endpoint asks for the handler and calls it:
app.MapPost("/orders", async (PlaceOrderBody body, PlaceOrderHandler handler, CancellationToken ct) =>
Created(await handler.HandleAsync(ToCommand(body), ct)));
The second version is better in ways you notice on the first day. "Go to definition" on HandleAsync lands in the handler. With Send, it lands on an interface inside a library, and you search for the request type to find out who handles it. In the myth as Apollodorus tells it, Ariadne gave Theseus a thread to fasten at the door of the labyrinth, so that he could find his way out again. A direct call is that thread. You can always follow it.
So the change is reasonable, the code is shorter, and the business logic didn't change by a line.
Why it fails
MediatR does two separate jobs, and the pull request replaced only one of them.
| Job | What it does | What the pull request did |
|---|---|---|
| Dispatch | Finds the handler for a request type at run time | Replaced it with a direct call |
| Pipeline | Runs behaviors around every handler | Deleted it |
The pipeline was three lines of registration, far from any handler:
builder.Services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssemblyContaining<PlaceOrder>();
cfg.AddOpenBehavior(typeof(LoggingBehavior<,>));
cfg.AddOpenBehavior(typeof(ValidationBehavior<,>));
cfg.AddOpenBehavior(typeof(TransactionBehavior<,>));
});
When AddMediatR went, these went with it. The behavior classes may even still be in the repository, compiling happily, called by nothing.
The handler in the companion sample saves an order and then reserves stock, in two writes. Here is what the same two bad requests do before and after the "clean-up":
| Request | With MediatR | Handler called directly |
|---|---|---|
| An order for -5 widgets | 400, nothing saved | 201, order saved, five widgets added to stock |
| An order for an item that is out of stock | 409, nothing saved | 409, but the order row and the widget it had already reserved stay in the database |
The second row is the quieter one. The client gets the right answer, and the database keeps half an order.
Nothing warned anyone, for two reasons:
- The compiler can't see it. Behaviors are open generics, resolved from the container at run time. Removing their registration is not a compile error.
- The tests never went through the pipeline. A handler's unit tests call the handler. They passed before and they pass now, because they never covered what the pipeline did.
Dionysius of Halicarnassus records the fable Menenius Agrippa told the Roman plebs when they walked out of the city. The parts of the body turn on the belly: the feet say the whole body rests on them, the hands that they do the work, the shoulders that they bear the burdens, and the belly, as far as they can see, does nothing. They stop serving it, and the whole body starves. MediatR looked like the belly. It sat in the middle and seemed only to pass requests along.
The fix: keep the pipeline, drop the dispatcher
You need three things: an interface, one small class per cross-cutting job, and one place that puts them together.
1. One interface
public interface IHandler<in TRequest, TResponse>
{
Task<TResponse> HandleAsync(TRequest request, CancellationToken ct);
}
A handler implements it. An endpoint asks for IHandler<PlaceOrder, OrderPlaced> and gets whatever the container decides that means.
2. One decorator per job
A decorator is a handler that wraps another handler. It does one thing and calls the next:
public sealed class ValidationDecorator<TRequest, TResponse>(
IHandler<TRequest, TResponse> inner,
IEnumerable<IValidator<TRequest>> validators) : IHandler<TRequest, TResponse>
{
public async Task<TResponse> HandleAsync(TRequest request, CancellationToken ct)
{
foreach (var validator in validators)
{
await validator.ValidateAndThrowAsync(request, ct);
}
return await inner.HandleAsync(request, ct);
}
}
public sealed class TransactionDecorator<TRequest, TResponse>(
IHandler<TRequest, TResponse> inner,
AppDb db) : IHandler<TRequest, TResponse>
{
public async Task<TResponse> HandleAsync(TRequest request, CancellationToken ct)
{
await using var transaction = await db.Database.BeginTransactionAsync(ct);
var response = await inner.HandleAsync(request, ct);
await transaction.CommitAsync(ct); // if the handler throws, disposing rolls back
return response;
}
}
EF Core already makes a single SaveChangesAsync atomic. This handler needs an explicit transaction because it does two separate writes, the order and then the stock, and they have to commit or roll back together.
The logging decorator has the same shape. If you compare each one with the MediatR behavior it replaces, the body is identical. Only the signature differs: inner.HandleAsync(request, ct) where the behavior had next().
3. One place that composes them
The built-in container has no method for decorating a registration, so the sample writes the wrapping out in a factory:
public static IServiceCollection AddHandler<TRequest, TResponse, THandler>(this IServiceCollection services)
where THandler : class, IHandler<TRequest, TResponse>
{
services.AddScoped<THandler>();
services.AddScoped<IHandler<TRequest, TResponse>>(sp =>
new LoggingDecorator<TRequest, TResponse>(
new ValidationDecorator<TRequest, TResponse>(
new TransactionDecorator<TRequest, TResponse>(
sp.GetRequiredService<THandler>(),
sp.GetRequiredService<AppDb>()),
sp.GetServices<IValidator<TRequest>>()),
sp.GetRequiredService<ILogger<LoggingDecorator<TRequest, TResponse>>>()));
return services;
}
Each use case is then one line, and the endpoint asks for the interface:
builder.Services.AddHandler<PlaceOrder, OrderPlaced, PlaceOrderHandler>();
app.MapPost("/orders", async (PlaceOrderBody body, IHandler<PlaceOrder, OrderPlaced> handler, CancellationToken ct) =>
Created(await handler.HandleAsync(ToCommand(body), ct)));
The order of the three is now something you can read: logging on the outside so it sees every outcome, validation next so an invalid request never opens a transaction, the transaction closest to the handler. With MediatR the same order was implied by the sequence of three registration calls.
With many handlers, the Scrutor package does the wrapping for every handler at once, with services.Decorate(typeof(IHandler<,>), typeof(LoggingDecorator<,>)). Mind the direction: in Scrutor the last Decorate call is the outermost, while in MediatR the first registered behavior is the outermost.
"Go to definition" still works. It lands on the interface, and "go to implementation" lists the handler and its three decorators, which is the whole truth about what runs.
What decorators ask of you
- A handler reached by its concrete type skips them. The broken endpoint above injects
PlaceOrderHandler; the fixed one injectsIHandler<PlaceOrder, OrderPlaced>. That is one type in a parameter list. Add a test that fails when an endpoint depends on a concrete handler, or it will happen again. - Not every handler wants every decorator. Most queries don't need a transaction. Split the interface into
ICommandHandlerandIQueryHandler, or let the decorator check for a marker interface on the request. - Failures need one translator. These decorators throw. One
IExceptionHandlerturns a validation failure into a 400 and an out-of-stock failure into a 409, following the policy in 400 or 422?. If you prefer result types over exceptions, the validation decorator returns a failed result without calling the next handler, and the transaction decorator has to roll back when it gets a failed result back. As written, it commits whenever the handler returns. The composition stays the same. - Order is your decision now. Write it in one place and comment why. Two registrations that wrap in different orders by accident are a bug that only shows under failure.
- This transaction decorator has limits. It assumes a top-level command and one database context. A decorated handler that calls another decorated handler would begin a second transaction on the same context. A retrying execution strategy needs the whole transaction inside the strategy. And a rollback cannot undo an HTTP call or a published message.
When to keep MediatR
Removing it is not always the right call.
| Your situation | Reasonable decision |
|---|---|
| A new service with a handful of use cases | Start without it |
| You rely on notifications, with several handlers per event, or on streaming requests | Keep it, or replace those separately; decorators only cover request and response |
| Hundreds of handlers and a pipeline that works | Stay. The migration costs weeks and changes no behaviour |
| You are on version 12 | It stays under its original Apache-2.0 licence; new releases are version 13 and later |
The licence is what started most of these conversations. Since version 13.0.0, released on 2 July 2025, MediatR is dual-licensed: under the Reciprocal Public License 1.5, or under a commercial licence. There is a free Community tier, for companies and individuals with less than 5 million US dollars in annual gross revenue, with further conditions. A missing licence key produces a log warning, not a failure. Read the current terms before you decide. Paying for a library your system depends on is a fair outcome. Removing it without knowing what it did is not a saving.
If you want a library and not sixty lines of your own, the source-generated Mediator and Wolverine are both MIT-licensed and both have their own way of wrapping handlers.
The rule
- Know what a library does before you remove it. MediatR dispatches requests and it wraps handlers. The second job has no line of code in any handler.
- Drop the dispatch, keep the wrapping. Inject the handler's interface, and give each cross-cutting job one decorator.
- Compose in one place, and test the composition. Send a request that should be refused and check that it was, through the real endpoint.
Frontinus, who ran Rome's water supply, described the city's aqueducts and then invited the reader to compare such indispensable structures with "the idle Pyramids". Validation, logging and transactions are that kind of structure: nobody admires them, and everything depends on them.
Run it yourself
The companion sample is a minimal ASP.NET Core API that runs entirely in Docker, next to PostgreSQL. It places the same order through three endpoints that share one handler: POST /mediatr/orders, POST /plain/orders and POST /orders. A small client sends two bad orders to each.
docker compose up -d --build
docker compose run --rm demo
The output on my machine:
1. An order for -5 widgets (the request is invalid)
MediatR with behaviors POST /mediatr/orders 400
Handler called directly POST /plain/orders 201
Handler with decorators POST /orders 400
2. An order for 1 widget and 1 gadget (gadgets are out of stock)
MediatR with behaviors POST /mediatr/orders 409
Handler called directly POST /plain/orders 409
Handler with decorators POST /orders 409
What each endpoint left behind (GET /stats). Each started with 10 widgets and no orders:
mediatr 0 order(s) saved, 10 widgets in stock
plain 2 order(s) saved, 14 widgets in stock
decorated 0 order(s) saved, 10 widgets in stock
The plain endpoint kept both bad orders. The first added five widgets to the shelf; the second took one before it failed. That is where 14 comes from. The other two endpoints behave identically, and one of them has no mediator.
The sample pins MediatR 12.5.0, the last release under the Apache-2.0 licence, so it runs without a licence key.
Further reading
- MediatR: licensing and editions
- Jimmy Bogard: AutoMapper and MediatR commercial editions launch today
- MediatR wiki: behaviors
- Scrutor: assembly scanning and decoration for Microsoft.Extensions.DependencyInjection
- dotnet/runtime issue 36021: decorator extension methods for IServiceCollection
- .NET: dependency injection guidelines
This article is part of Justified Complexity: Building Backends One Decision at a Time.
Updated 2026-11-11, after a review: the note on result types now says that the transaction decorator must roll back on a failed result; added why this handler needs an explicit transaction and what the transaction decorator assumes; three sentences are worded more exactly. In the sample, a null order line is now refused with a 400, the demo client checks its own output, and the Location of a created order resolves.