📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

What is the Mediator pattern, and how does MediatR implement it with request handlers and pipeline behaviours? When is it indirection for nothing, what changed with MediatR's licence, and what alternatives would you consider for a new .NET 10 service?

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.

Mid-Level Theory Intermediate cqrs design-patterns licensing mediator mediatr pipeline-behaviors

🎯 Key points

  • GoF Mediator: colleagues communicate through a mediator instead of referencing each other, turning many-to-many coupling into many-to-one (dialog with controls, chat room)
  • MediatR is closer to an in-process command/query dispatcher: Send(IRequest<T>) to exactly one IRequestHandler; Publish(INotification) to many handlers
  • IPipelineBehavior<TRequest,TResponse> wraps every handler (validation, logging, transactions): a Decorator applied generically
  • Costs: 'Go to definition' lands on Send, not the handler; extra allocations and reflection-based resolution; handlers can call Send recursively and hide dependencies
  • Indirection for nothing: a controller that only calls Send on a handler that calls a repository; an interface you inject directly gives the same decoupling
  • Licence: from v13.0 (2 July 2025) MediatR is dual-licensed RPL-1.5 / commercial under Lucky Penny Software; v14.x is current; 12.5.0 is the last Apache 2.0 release
  • Community edition is free for organisations under US$5M gross annual revenue, non-profits, education and non-production; larger companies need a paid tier and a licence key
  • Alternatives: inject handler interfaces directly, generic decorators via Scrutor, source-generated mediators (no reflection), or stay on 12.5.0 accepting no future fixes

⏱ 30-second answer

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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"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 Send a request object and it finds exactly one IRequestHandler for it, or you Publish a notification to several handlers. The genuinely useful part is IPipelineBehavior: 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 on Send; new developers have to learn a convention to find the code; and handlers can call Send from inside other handlers, which hides dependencies. Injecting IGetOrderHandler directly 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 Send style, 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 vs MediatR

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

Licensing status (as of November 2026)

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

When it earns its place, and when not

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

Production example

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.

πŸ” What the interviewer is checking

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

  • Explains GoF Mediator as reducing many-to-many coupling.
  • Describes MediatR as a dispatcher and pipeline behaviours as decorators.
  • Names concrete costs: navigation, hidden dependencies, allocation.
  • Knows MediatR moved to dual RPL-1.5/commercial licensing in July 2025 and what that means.
  • Offers concrete alternatives.

Red flags

  • Says MediatR is required for clean architecture or CQRS.
  • Unaware of the licence change.
  • Puts business logic in behaviours or uses notifications as durable events.

πŸ“š Learn in depth

1. The GoF structure

            Β«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.

2. What MediatR actually does

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.

3. Costs you should be able to name

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

4. Licence details that matter in practice

  • The change was announced by Jimmy Bogard and took effect with MediatR 13.0 on 2 July 2025; AutoMapper moved at the same time.
  • The open-source option is RPL-1.5, a copyleft licence many organisations won't accept for closed-source products, so most companies choose between the Community edition and a paid tier.
  • Paid tiers are subscriptions by number of developers (Standard 1–10, Professional 11–50, Enterprise unlimited).
  • A licence key is set via cfg.LicenseKey; check the current terms on mediatr.io before deciding, because pricing and conditions can change.

5. Alternatives

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

6. Notifications are not durable events

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.

Try it yourself

  1. Implement the address-form mediator with three colleagues and compare with a version where colleagues reference each other.
  2. Build a MediatR handler with logging and validation behaviours; put a breakpoint in each and confirm the order.
  3. Rewrite the same endpoint with an injected ICommandHandler<,> and two Scrutor decorators.
  4. BenchmarkDotNet both versions of a trivial handler and compare allocations per call.
  5. Read the current licence terms on mediatr.io and write a one-paragraph recommendation for your organisation.

πŸ’» Code

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));

⚠ Common mistakes

  • Mistake: Adopting MediatR by default for every new API. Why it is wrong: With no shared pipeline, it adds indirection, a dependency and possibly a licence cost for nothing. Instead: Start with injected handlers; add a dispatcher only when a pipeline across many handlers justifies it.
  • Mistake: Upgrading MediatR past 12.5.0 without checking the licence. Why it is wrong: v13+ is RPL-1.5 or commercial, and organisations over the Community threshold need a paid licence. Instead: Run a licence review, then choose a tier, stay on 12.5.0 knowingly, or migrate.
  • Mistake: Injecting 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.
  • Mistake: Using 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.
  • Mistake: Calling MediatR "the Mediator pattern" without distinction. Why it is wrong: It misses what the GoF pattern solves (tangled colleagues) and when it fits. Instead: Describe MediatR as an in-process dispatcher with pipeline behaviours.
  • Mistake: Building a GoF mediator that accumulates every rule. Why it is wrong: It becomes a god object that changes for every feature. Instead: Keep mediators small and per-collaboration; split when they grow.
  • Mistake: Putting business logic in pipeline behaviours. Why it is wrong: Behaviour runs invisibly for every request and is hard to reason about. Instead: Keep behaviours for cross-cutting concerns only.

πŸ› Senior insight: trade-offs

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.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate says pipeline behaviours wrap every handler Why: Checks that pipeline behaviours are recognised as decorators and how decorators are registered
    How to answer

    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.

  2. When: Candidate calls MediatR indirection for nothing in simple services Why: Checks judgement about abstraction layers that add no value
    How to answer

    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.

  3. When: Candidate talks about requests and notifications as commands and events Why: Checks the Command pattern and the command vs event distinction behind IRequest and INotification
    How to answer

    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.

    • GoF style: the command has Execute() (and Undo()); an invoker runs it without knowing what it does. Good for undo stacks and macros.
    • Modern style: an immutable record (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.

πŸ›  Real-world problems: how you handle them

Licence review blocked the MediatR 13 upgrade
Situation
Order platform at [company] (revenue above US$5M) with [~120] MediatR handlers and two pipeline behaviours across [4] services. Dependabot raised an upgrade from 12.5.0 to 13.x.
Signals
The licence-compliance check in CI flagged the RPL-1.5 licence on the new package; legal asked for a decision before any upgrade; the application logged a missing licence key warning in a test environment where someone had upgraded.
Investigation
Inventoried usage with a Roslyn-based search: [~120] `IRequestHandler` implementations, two behaviours (validation, logging), [6] `INotification` handlers, and [14] handlers injecting `IMediator` to call other handlers. Estimated licence cost against migration effort and ran BenchmarkDotNet on three hot endpoints to compare dispatch overhead.
Resolution
Immediate: pinned MediatR to 12.5.0 and documented the decision. Real fix: introduced `ICommandHandler<,>`/`IQueryHandler<,>` interfaces and two Scrutor decorators, migrated handlers service by service behind the same endpoints, replaced handler-to-handler `Send` calls with explicit dependencies, and moved the six notifications to explicit in-process calls or the outbox.
Prevention
Licence policy in CI that fails on non-approved licences; an ADR recording why the platform uses explicit handlers; an analyser banning `IMediator` injection in new code during the migration.

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%].

↩ Usually asked after

More in Behavioral Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me