GoF Mediator (colleagues talk through a mediator) vs MediatR as an in-process request dispatcher, IRequest/IRequestHandler, INotification, IPipelineBehavior for validation and logging, costs (indirection, navigation, reflection), MediatR's July 2025 move to dual RPL-1.5/commercial licensing under Lucky Penny Software and the Community edition, and alternatives: direct handler injection, decorators, source-generated mediators.
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.
"I'd separate the GoF pattern from the library, because they're not quite the same thing. The GoF Mediator is about objects that would otherwise all reference each other. In a dialog, the country dropdown, the state dropdown, the postcode field and the submit button all affect each other; instead of each holding references to the others, they all talk to the dialog, and the dialog coordinates. Many-to-many becomes many-to-one. MediatR uses the name, but what it actually gives you is an in-process dispatcher: you
Senda request object and it finds exactly oneIRequestHandlerfor it, or youPublisha notification to several handlers. The genuinely useful part isIPipelineBehavior: a generic wrapper around every handler where you put validation, logging, metrics or a transaction once. That's the Decorator pattern applied to all handlers at once.Where it goes wrong is when there's nothing to mediate. An endpoint calls
_mediator.Send(new GetOrder(id)), the handler calls a repository, and that's it. You've lost 'go to definition', because it lands onSend; new developers have to learn a convention to find the code; and handlers can callSendfrom inside other handlers, which hides dependencies. InjectingIGetOrderHandlerdirectly gives you the same testability. On licensing: since version 13, released on 2 July 2025, MediatR is dual-licensed under the Reciprocal Public License 1.5 or a commercial licence from Lucky Penny Software, and the current line is 14.x. There's a free Community edition for organisations under US$5 million gross annual revenue, non-profits and education; above that you need a paid tier and a licence key. Version 12.5.0 is the last Apache 2.0 release, so staying on it is legal but means no future fixes.For a new .NET 10 service I'd start with plain handler interfaces injected into endpoints, and add cross-cutting behaviour with decorators or endpoint filters. If a team really wants the
Sendstyle, a source-generated mediator removes the reflection and keeps compile-time checking. The mistake I see is adopting MediatR because it's 'clean architecture', not because there's a pipeline worth centralising. Use a mediator when you need one pipeline around many handlers; otherwise it's a level of indirection you pay for on every code read."
| GoF Mediator | MediatR | |
|---|---|---|
| Problem solved | Many objects tangled together | Decoupling callers from handlers; one pipeline for all |
| Communication | Colleagues β mediator, often both ways | Caller β dispatcher β one handler (or many for notifications) |
| Mediator knows | Its colleagues and coordination rules | Nothing about the domain; resolves handlers from DI |
| Typical example | UI dialog, air-traffic control, chat room | Send(new PlaceOrder(...)) in a web API |
| Version | Licence | Notes |
|---|---|---|
| 12.5.0 and earlier | Apache 2.0 | Last permissive release; no further fixes |
| 13.0 (2 July 2025) onwards, 14.x current | Dual RPL-1.5 / commercial (Lucky Penny Software) | Licence key configured in AddMediatR; tiers by team size |
| Community edition | Commercial licence, free | Under US$5M gross annual revenue, non-profits, education, non-production |
| Keep or adopt MediatR | Prefer direct handlers |
|---|---|
| Many handlers sharing validation, logging, transaction behaviours | A few endpoints with simple logic |
| Existing codebase built around it, licence cost acceptable | New service, small team |
| You want notifications fanned out in-process | One handler per call, no fan-out |
A licence review for an organisation above the Community threshold flagged the upgrade to MediatR 13. The service had about 120 handlers but only two pipeline behaviours (validation and logging). Replacing Send with injected handler interfaces and two generic Scrutor decorators took about [three sprints], removed the licence cost, and cut request allocations by roughly 10% in BenchmarkDotNet runs of the hot endpoints.
Checks whether the candidate can separate the GoF pattern from MediatR, judge when a dispatcher adds value, and knows the current licensing situation.
Green flags
Red flags
Β«interfaceΒ» IMediator
Notify(sender, event)
β²
AddressFormMediator
β β β
βΌ βΌ βΌ
CountrySelect StateSelect PostcodeBox (colleagues)
each holds only a reference to the mediator
Without it, N colleagues can need up to NΓ(Nβ1) references. With it, each colleague knows one mediator, and the coordination rules live in one place. The risk is the mediator becoming a god object.
Endpoint ββSend(PlaceOrder)βββΆ IMediator
β resolves from DI
βΌ
IPipelineBehavior #1 (logging)
βββΆ IPipelineBehavior #2 (validation)
βββΆ IRequestHandler<PlaceOrder, OrderId>
IRequest<TResponse> β exactly one IRequestHandler<TRequest, TResponse>.INotification β all INotificationHandler<T> implementations, run sequentially by default.IPipelineBehavior<TRequest, TResponse> β open generic wrappers registered with cfg.AddOpenBehavior(typeof(LoggingBehavior<,>)). Each calls next() to continue; order is registration order.Handler resolution uses DI plus cached generic wrapper types built with reflection at first use.
| Cost | Why |
|---|---|
| Navigation | Send hides the handler; IDE "go to implementation" on the request type helps but it's a convention to learn |
| Hidden dependencies | A handler that injects IMediator can send anything; its constructor no longer lists what it needs |
| Allocation and dispatch | Wrapper objects, behaviour chain delegates and DI resolution per call; small but measurable on hot paths |
| Trimming / Native AOT | Reflection-based handler discovery needs care; source-generated alternatives avoid it |
| Licence | Commercial terms for v13+ above the Community threshold |
cfg.LicenseKey; check the current terms on mediatr.io before deciding, because pricing and conditions can change.| Alternative | How it works | Trade-off |
|---|---|---|
| Inject handler interfaces | ICommandHandler<PlaceOrder, OrderId> injected into the endpoint |
Explicit, traceable; cross-cutting concerns need decorators |
| Generic decorators (Scrutor) | services.Decorate(typeof(ICommandHandler<,>), typeof(LoggingHandler<,>)) |
Same pipeline idea, no dispatcher |
| Endpoint filters / middleware | ASP.NET Core pipeline for HTTP-level concerns | Only for HTTP entry points |
| Source-generated mediator | Compile-time generated dispatch, no reflection | Another dependency; check its licence |
| Stay on MediatR 12.5.0 | Apache 2.0, works today | No security or bug fixes going forward |
Publish runs handlers in-process, usually sequentially; if one throws, later ones may not run, and nothing survives a crash. Treat INotification as in-process Observer, not as integration events; use an outbox and a broker for those.
ICommandHandler<,> and two Scrutor decorators.MediatR style: a request, a handler and a pipeline behaviour.
namespace Orders;
using MediatR;
public sealed record PlaceOrder(Guid CustomerId, IReadOnlyList<OrderLine> Lines) : IRequest<Guid>;
public sealed record OrderLine(string Sku, int Quantity);
public sealed class PlaceOrderHandler(OrdersDbContext db) : IRequestHandler<PlaceOrder, Guid>
{
public async Task<Guid> Handle(PlaceOrder request, CancellationToken ct)
{
var order = Order.Create(request.CustomerId, request.Lines);
db.Orders.Add(order);
await db.SaveChangesAsync(ct);
return order.Id;
}
}
// One behaviour wraps every handler: this is the part worth centralising
public sealed class LoggingBehavior<TRequest, TResponse>(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
: IPipelineBehavior<TRequest, TResponse> where TRequest : notnull
{
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken ct)
{
logger.LogInformation("Handling {Request}", typeof(TRequest).Name);
var response = await next();
logger.LogInformation("Handled {Request}", typeof(TRequest).Name);
return response;
}
}
// Program.cs (MediatR 13+; licence key from configuration, not source control)
// builder.Services.AddMediatR(cfg =>
// {
// cfg.LicenseKey = builder.Configuration["MediatR:LicenseKey"];
// cfg.RegisterServicesFromAssemblyContaining<PlaceOrderHandler>();
// cfg.AddOpenBehavior(typeof(LoggingBehavior<,>));
// });
// app.MapPost("/orders", (PlaceOrder cmd, ISender sender, CancellationToken ct) => sender.Send(cmd, ct));
The same thing without a dispatcher: handler interfaces injected directly, and a generic decorator for the pipeline.
namespace Orders;
public interface ICommandHandler<in TCommand, TResult>
{
Task<TResult> HandleAsync(TCommand command, CancellationToken ct);
}
public sealed record PlaceOrderCommand(Guid CustomerId, IReadOnlyList<OrderLine> Lines);
public sealed class PlaceOrderCommandHandler(OrdersDbContext db) : ICommandHandler<PlaceOrderCommand, Guid>
{
public async Task<Guid> HandleAsync(PlaceOrderCommand cmd, CancellationToken ct)
{
var order = Order.Create(cmd.CustomerId, cmd.Lines);
db.Orders.Add(order);
await db.SaveChangesAsync(ct);
return order.Id;
}
}
// Decorator = pipeline behaviour without a mediator
public sealed class LoggingCommandHandler<TCommand, TResult>(
ICommandHandler<TCommand, TResult> inner,
ILogger<LoggingCommandHandler<TCommand, TResult>> logger) : ICommandHandler<TCommand, TResult>
{
public async Task<TResult> HandleAsync(TCommand command, CancellationToken ct)
{
logger.LogInformation("Handling {Command}", typeof(TCommand).Name);
var result = await inner.HandleAsync(command, ct);
logger.LogInformation("Handled {Command}", typeof(TCommand).Name);
return result;
}
}
// Program.cs
// builder.Services.AddScoped<ICommandHandler<PlaceOrderCommand, Guid>, PlaceOrderCommandHandler>();
// builder.Services.Decorate(typeof(ICommandHandler<,>), typeof(LoggingCommandHandler<,>)); // Scrutor
//
// "Go to definition" on the injected interface now leads straight to the handler:
// app.MapPost("/orders", (PlaceOrderCommand cmd, ICommandHandler<PlaceOrderCommand, Guid> handler, CancellationToken ct)
// => handler.HandleAsync(cmd, ct));
IMediator into handlers and sending other requests from inside them. Why it is wrong: Dependencies are hidden and request chains become hard to follow or accidentally recursive. Instead: Inject the specific services a handler needs; keep Send at the edges.INotification for integration events that must reach other services. Why it is wrong: In-process, not durable, lost on a crash. Instead: Use an outbox and a message broker.The decision isn't "MediatR good or bad", it's whether a uniform pipeline around many handlers is worth the indirection and, now, the licence. For an existing codebase with dozens of behaviours, paying for MediatR or staying on 12.5.0 is often cheaper than migrating. For a new service, I default to explicit handlers and decorators, because the next developer can follow the code with "go to definition".
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Direct handler injection | New services, few cross-cutting concerns | Decorators needed for pipelines | Many behaviours and fan-out notifications |
| MediatR (licensed or Community) | Large existing usage, behaviours load-bearing | Indirection, licence for larger orgs | Small services; teams unwilling to accept the terms |
| Stay on MediatR 12.5.0 | Short-term while deciding | No future fixes | Long-lived products with security requirements |
| Source-generated mediator | Want Send style without reflection, AOT |
Another dependency to vet | Team happy with plain DI |
| GoF mediator class | UI or workflow with tangled collaborators | Risk of god object | Simple request/handler dispatch |
Measure before arguing about performance: BenchmarkDotNet on a trivial handler shows the dispatch cost is real but small; the bigger costs are navigation and hidden dependencies, which you see in onboarding time and review comments.
Decorator wraps an object in another object that implements the same interface, adds behaviour before or after delegating, and is invisible to callers. Decorators stack: logging around caching around the real repository. Each concern is one small class, so the original stays untouched (Open/Closed).
.NET uses it everywhere: GZipStream(BufferedStream(FileStream)), CryptoStream, and DelegatingHandler pipelines in HttpClient.
The built-in container has no Decorate method. You register the inner type concretely and the interface with a factory delegate, use a keyed inner service, or use Scrutor's Decorate<TService, TDecorator>().
The trade-off is that order matters and long chains are harder to debug.
Over-engineering is complexity that today's requirements do not justify. I detect it through symptoms with numbers behind them: a one-field change touching many files, interfaces with one implementation, configuration options nobody sets, patterns like CQRS or event sourcing without the problems they solve, and microservices that always deploy together. I reverse it incrementally rather than with a rewrite: inline single-use abstractions, merge layers that only pass data through, consolidate services that share a release cycle, and delete unused options, each step behind tests. I also address why it happened, because otherwise it grows back.
Command turns a request into an object. Once "place this order" or "rename this file" is data rather than a method call, you can queue it, retry it, log it for audit, or undo it.
Execute() (and Undo()); an invoker runs it without knowing what it does. Good for undo stacks and macros.PlaceOrder) plus a separate handler (ICommandHandler<PlaceOrder>). Splitting data from behaviour lets the command be serialised to a Channel<T>, Azure Service Bus or an audit table.A command is an imperative request with one handler that may reject it; an event is a past-tense fact with any number of handlers.
The trade-off: an extra type per operation and indirection, so plain method calls are fine when you need none of queuing, retry, undo or audit.
How to tell it (STAR)
**S:** At [company], a routine Dependabot PR would have moved our order platform onto MediatR 13, which our licence check flagged because we were above the Community edition threshold. **T:** I had to recommend whether to buy, stay or migrate, without disrupting delivery. **A:** I inventoried our usage and found [120] handlers but only two behaviours that really needed a pipeline, and [14] handlers hiding dependencies by calling `Send`. I pinned 12.5.0, wrote an ADR, and led a migration to injected handler interfaces with two generic decorators, one service per sprint. **R:** We finished in [three sprints] with no endpoint changes, avoided [the licence cost], made handler dependencies explicit, and cut allocations on hot endpoints by about [10%].
Last updated 18 Nov 2026.