An architecture decision on mediators in .NET 10: what MediatR gives a vertical-slice codebase, the indirection and performance costs, built-in alternatives (endpoint filters, direct handler injection), source-generated and Wolverine alternatives, MediatR's commercial licensing as of late 2026, and an incremental migration plan.
In a vertical-slice app, a mediator is a dispatch convention, not an architecture. MediatR gives a uniform handler shape and pipeline behaviours for validation, logging and transactions. It costs indirection (you can't go-to-definition from endpoint to handler), some dispatch overhead and ceremony.
ASP.NET Core already has most of it: inject the handler directly, use endpoint filters and decorators for cross-cutting concerns. Since v13 (July 2025) MediatR is dual-licensed: RPL 1.5 or a commercial licence, with a free Community edition for organisations under US$5M revenue. Alternatives include source-generated mediators and Wolverine.
The trade-off: consistency and a familiar pattern versus a dependency, licence management and hidden flow.
"I'd start by asking what problem the mediator solves for us. In-process,
mediator.Send(new CreateOrder(...))does the same thing as callingcreateOrderHandler.HandleAsync(...): it just resolves the handler from DI for you. The real benefits are a uniform handler shape, so every slice looks the same, and pipeline behaviours, so validation, logging and transactions wrap every request without each handler repeating them. The costs are that you lose go-to-definition from the endpoint to the handler, request types multiply, stack traces get deeper, and every call goes through DI resolution of generic types. The overhead is small per request, typically microseconds, so it's rarely the deciding factor; readability and the dependency are.Then I'd check what we already have. With Minimal APIs I can inject the handler straight into the endpoint, and endpoint filters or a decorator registered in DI give me validation and logging. That covers most of what MediatR's behaviours do, with no extra package. On licensing: since MediatR 13 in July 2025 it's dual-licensed under the Reciprocal Public Licence or a commercial licence from Lucky Penny Software, with a free Community edition for companies under five million US dollars gross revenue. For a larger organisation, that's a procurement decision and a licence key to manage. For example, at [company] we [evaluated this in an ADR], [spiked direct handler injection with endpoint filters on two slices], and [chose X because Y].
If the team still wants the mediator shape, a source-generated mediator gives the same API with no reflection and better AOT support, and Wolverine is an option if we also want messaging and an outbox. To move an existing codebase off MediatR, I'd introduce our own small
IHandler<TRequest, TResponse>interface, convert behaviours into decorators or filters, and migrate slice by slice behind tests.The mistake I see is adopting MediatR by reflex and calling it CQRS. It's a convenience, and I'd make it a deliberate choice."
| Aspect | MediatR | Direct handler injection + filters |
|---|---|---|
| Handler shape | Enforced IRequestHandler<,> |
Your own interface or convention |
| Cross-cutting | IPipelineBehavior<,> |
Endpoint filters, decorators |
| Navigation | Endpoint -> request -> handler (indirect) | Endpoint -> handler (direct) |
| Dispatch | DI resolution of closed generics per call | Constructor injection |
| Native AOT | Reflection-based registration needs care | Fully AOT-friendly |
| Licence | RPL 1.5 or commercial (v13+) | None |
| Option | When it fits | Watch out for |
|---|---|---|
| No mediator, direct injection | Most vertical-slice web apps | Need your own conventions |
| MediatR 13+ (Community or paid) | Existing heavy usage, team familiarity | Licence key, revenue threshold, cost per team |
| Pin MediatR 12.x (Apache 2.0) | Short-term, while migrating | No new fixes or features |
Source-generated mediator (Mediator by martinothamar) |
Want the shape without reflection | Smaller ecosystem |
| Wolverine | Also need messaging, outbox, sagas | Bigger framework to learn |
A [retail] API with 140 MediatR handlers moved to direct injection over four sprints. Average request overhead dropped by about 3 microseconds, which was irrelevant; what mattered was that onboarding time for new engineers fell because endpoints now navigated straight to handlers, and the organisation avoided a licence purchase for 30 developers.
Checks whether the candidate evaluates a popular library on its merits, knows the built-in alternatives and the current licensing facts, and can plan a low-risk migration.
Green flags
Red flags
Endpoint --Send(CreateOrder)--> IMediator
| resolve IPipelineBehavior<CreateOrder, Result>[] from DI
| resolve IRequestHandler<CreateOrder, Result> from DI
v
Logging -> Validation -> Transaction -> Handler
The GoF Mediator pattern centralises communication between colleagues. MediatR's in-process use is closer to a command dispatcher plus a pipeline. Nothing crosses a process boundary, so it doesn't decouple deployment or teams; it decouples types.
Minimal API endpoint
-> endpoint filters (validation, logging) // IEndpointFilter, AddEndpointFilter
-> handler injected as a parameter // [FromServices] implicit
-> decorators registered in DI for the handler // transactions, caching
IEndpointFilter) run around Minimal API handlers with access to arguments and results.Decorate) wrap handler interfaces for concerns not tied to HTTP, such as background jobs.MediatR dispatch costs a dictionary lookup, a DI resolution of closed generic types, and a delegate chain per behaviour: microseconds and some allocations per request. This rarely matters compared with a database call, but assembly scanning for registration and generic resolution complicate trimming and Native AOT. Source-generated mediators generate a switch at compile time, removing reflection.
RPL is reciprocal: using it in a closed-source commercial product generally isn't viable, so most companies over the threshold need a paid licence.
Step 1: add IHandler<TRequest, TResponse> in your own shared project
Step 2: adapter: MediatR handler implements both interfaces during migration
Step 3: move behaviours -> decorators / endpoint filters, with tests asserting order
Step 4: change endpoints slice by slice to inject IHandler<,> directly
Step 5: remove MediatR registration and package; architecture test bans the namespace
Notifications (INotification with multiple handlers) need a replacement too: domain event dispatch, or an in-process bus.
mediator.Send against a direct handler call with BenchmarkDotNet and compare allocations.MediatR.A slice without a mediator: a handler interface, a validation endpoint filter and a transaction decorator.
namespace Shop.Shared;
public interface IHandler<in TRequest, TResponse>
{
Task<TResponse> HandleAsync(TRequest request, CancellationToken ct);
}
namespace Shop.Features.Orders;
using FluentValidation;
using Shop.Shared;
public sealed record CreateOrder(Guid CustomerId, IReadOnlyList<Guid> ProductIds);
public sealed record OrderCreated(Guid OrderId);
public sealed class CreateOrderValidator : AbstractValidator<CreateOrder>
{
public CreateOrderValidator() => RuleFor(x => x.ProductIds).NotEmpty();
}
public sealed class CreateOrderHandler(ShopDbContext db) : IHandler<CreateOrder, OrderCreated>
{
public async Task<OrderCreated> HandleAsync(CreateOrder request, CancellationToken ct)
{
var order = Order.Create(request.CustomerId, request.ProductIds);
db.Orders.Add(order);
await db.SaveChangesAsync(ct);
return new OrderCreated(order.Id);
}
}
// Validation as an endpoint filter instead of a pipeline behaviour.
public sealed class ValidationFilter<T>(IValidator<T> validator) : IEndpointFilter
{
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext ctx, EndpointFilterDelegate next)
{
var arg = ctx.Arguments.OfType<T>().Single();
var result = await validator.ValidateAsync(arg, ctx.HttpContext.RequestAborted);
return result.IsValid ? await next(ctx) : TypedResults.ValidationProblem(result.ToDictionary());
}
}
public static class CreateOrderEndpoint
{
public static void Map(IEndpointRouteBuilder app) =>
app.MapPost("/orders", async (CreateOrder cmd, IHandler<CreateOrder, OrderCreated> handler, CancellationToken ct) =>
TypedResults.Ok(await handler.HandleAsync(cmd, ct))) // go-to-definition lands on the handler interface
.AddEndpointFilter<ValidationFilter<CreateOrder>>();
}
// Program.cs
builder.Services.AddScoped<IHandler<CreateOrder, OrderCreated>, CreateOrderHandler>();
builder.Services.AddScoped<IValidator<CreateOrder>, CreateOrderValidator>();
// Cross-cutting behaviour for non-HTTP callers too, via Scrutor:
builder.Services.Decorate(typeof(IHandler<,>), typeof(LoggingHandlerDecorator<,>));
CreateOrderEndpoint.Map(app);
GetOrderQuery handlers that load full tracked aggregates through the write model, so they pay MediatR's ceremony and get none of CQRS's benefits. Instead: decide each separately: separate read models (projections, AsNoTracking DTO queries) are the CQRS decision; the mediator is an optional dispatch convenience.mediator.Send for other handlers. Why it is wrong: creates hidden call chains and nested transactions. Instead: extract shared logic into domain or application services.INotification handlers during migration. Why it is wrong: side effects silently stop. Instead: inventory notifications and replace with domain event dispatch.This is a classic reversible decision that teams treat as permanent. I'd frame it in an ADR around four things: what the mediator buys us that the framework doesn't (usually only uniform shape and notifications), the licence position for our organisation, team familiarity, and the cost of exit.
Where a mediator genuinely adds value: a large team new to vertical slices that benefits from one enforced handler shape; many non-HTTP entry points (queue consumers, scheduled jobs, gRPC) that all need the same validation and transaction pipeline; or heavy use of multi-handler notifications. Where it doesn't: a small, experienced team with Minimal APIs, where filters and direct injection are clearer.
Exit cost is concrete and worth estimating up front: the number of handlers and behaviours to convert (a codemod or Roslyn script helps), notifications whose side effects must be preserved, pipeline ordering that tests must pin down, and retraining for engineers used to Send. On the other side of the ledger: onboarding time lost to indirection, time to trace a request in code review, and licence fees. US$489 a year for a small team is cheap if it saves real work; for 200 developers, or a product shipped to customers under RPL concerns, the calculation changes.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Direct injection + filters/decorators | Experienced team, Minimal APIs | Own conventions | Team wants a strict, familiar shape |
| MediatR (licensed) | Large existing usage, notifications used heavily | Licence fee, key management | Closed product over threshold without budget |
| Source-generated mediator | Want the shape, AOT, no reflection | Smaller community | Need MediatR-specific ecosystem packages |
| Wolverine | Also need durable messaging and outbox | Framework adoption | Simple in-process dispatch only |
I'd measure onboarding time, time to trace a request in code reviews, and licence cost, rather than dispatch microseconds.
The GoF Mediator stops objects talking to each other directly: colleagues send messages to a mediator, which turns many-to-many coupling into many-to-one (a dialog coordinating its controls).
MediatR is really an in-process request dispatcher: Send(IRequest<T>) goes to exactly one handler, Publish(INotification) to many, and IPipelineBehavior wraps every handler with validation, logging or transactions.
It's indirection for nothing when an endpoint just sends to a handler that calls a repository: injecting the handler gives the same decoupling, and "go to definition" still works.
Licensing: since v13 (July 2025) MediatR is dual RPL-1.5 / commercial under Lucky Penny Software, free (Community edition) under US$5M revenue; 12.5.0 is the last Apache 2.0 version.
Alternatives: direct handler injection with decorators, or a source-generated mediator. The trade-off is uniform pipelines vs traceable, explicit code.
Vertical Slice Architecture organises code by feature, not by layer: each use case — PlaceOrder, GetOrderSummary — is a slice containing its request, validator, handler, data access and response, often in one folder or file.
Compared with Clean Architecture, a feature change touches one folder instead of four projects. The trade-off: less shared structure, so without a rich domain model, rules can be duplicated across slices.
Microsoft.Extensions.DependencyInjection has no Decorate method (unlike Autofac or Lamar), so you register the inner implementation as its concrete type (or under a key) and the interface with a factory that wraps it: AddScoped<IProductRepository>(sp => new CachingProductRepository(sp.GetRequiredService<EfProductRepository>(), ...)). Three things decide whether it's correct. Lifetimes: the decorator must not outlive its inner, or you've built a captive dependency. Disposal: the container disposes everything it created, so the decorator mustn't dispose the inner. Order: the last wrapper registered is the outermost, so I keep one concern per decorator and test the resolved chain. Scrutor's Decorate does the descriptor surgery for you, keeps the lifetime and handles many registrations at once. The trade-off is a small library dependency and start-up reflection versus hand-written factories that are explicit, which I still prefer for one or two decorators.
How to tell it (STAR)
**S:** At [company], an upgrade pulled MediatR 13 into a [policy] API with [~150] handlers, and our licence scanner flagged RPL. **T:** As [senior engineer], I had to keep releases flowing and recommend a path. **A:** I pinned 12.x the same day, inventoried usage, priced the commercial tiers, and spiked direct injection on two slices to measure effort. I wrote an ADR with both options; some of the team preferred paying, so we agreed criteria, and I committed to the decision the architecture forum made. **R:** We migrated in [four] sprints with no regressions, saved [~US$X] a year in licences, and new engineers reported [faster] code navigation.
Last updated 23 Nov 2026.