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

📚 Interview question

Your team is starting a vertical-slice .NET 10 codebase and someone proposes MediatR for every request. How do you evaluate whether you need a mediator at all? Cover the cost of indirection, pipeline behaviours versus ASP.NET Core filters, MediatR's licence change, and how you would move an existing codebase off it.

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.

Senior Architecture Advanced architecture cqrs licensing mediatr minimal-apis vertical-slice

🎯 Key points

  • A mediator decouples the caller from the handler type; in-process it's a dispatch convention, not an architecture, and not CQRS
  • Benefits: uniform handler shape, pipeline behaviours for validation, logging, transactions, multi-handler notifications
  • Costs: indirection (no go-to-definition from endpoint to handler), DI dispatch overhead, request-type ceremony
  • Built-in alternatives: inject the handler directly, endpoint filters and MVC filters for cross-cutting concerns, DI decorators
  • MediatR 13 (July 2025) moved to Lucky Penny Software: RPL 1.5 or commercial; free Community edition for organisations under US$5M gross revenue, non-profits, education and non-production use
  • Alternatives: source-generated mediators (Mediator by martinothamar), Wolverine, or pinning the last Apache 2.0 release (12.x) temporarily
  • Migration: own IHandler<TRequest,TResponse>, behaviours to decorators/filters, notifications to domain event dispatch, slice by slice
  • Decide in an ADR: licence cost, team familiarity, exit cost and readability, not microseconds

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd start by asking what problem the mediator solves for us. In-process, mediator.Send(new CreateOrder(...)) does the same thing as calling createOrderHandler.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."


What you get and what it costs

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

Options as of November 2026

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

Production example

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.

🔍 What the interviewer is checking

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

  • Explains what a mediator does in-process and what it doesn't decouple
  • Names endpoint filters and decorators as alternatives
  • States MediatR's dual licence and Community threshold accurately
  • Offers a slice-by-slice migration with an adapter interface
  • Frames it as a reversible, ADR-recorded decision

Red flags

  • "We always use MediatR for CQRS"
  • Unaware of the licence change
  • Big-bang rewrite plan or arguing purely on performance

📚 Learn in depth

1. What a mediator does in-process

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.

2. The built-in equivalents

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
  • Endpoint filters (IEndpointFilter) run around Minimal API handlers with access to arguments and results.
  • MVC action filters do the same for controllers.
  • Decorators (manual factory or Scrutor's Decorate) wrap handler interfaces for concerns not tied to HTTP, such as background jobs.

3. Performance and AOT

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.

4. Licensing history (check before quoting)

  • MediatR up to 12.x: Apache 2.0.
  • April 2025: Jimmy Bogard announced MediatR and AutoMapper would become commercial.
  • July 2025: MediatR 13 released under Lucky Penny Software with a dual licence: the Reciprocal Public Licence 1.5 (RPL) or a commercial licence. A free Community edition covers organisations under US$5M gross annual revenue (plus non-profits, education and non-production use); paid tiers are priced by team size. A licence key is configured in code, and unlicensed use logs a warning rather than failing.
  • Later versions (v14 was current at time of writing) continue the same model. Check mediatr.io for current terms before advising a client.

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.

5. Migrating off MediatR

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.

Try it yourself

  1. Benchmark mediator.Send against a direct handler call with BenchmarkDotNet and compare allocations.
  2. Rewrite one slice with direct injection and an endpoint filter for FluentValidation.
  3. Write a decorator for transactions and register it with Scrutor; assert the order of decorators in a test.
  4. Add an architecture test (NetArchTest or ArchUnitNET) that fails if any type references MediatR.
  5. Publish the app with Native AOT and compare trimming warnings with and without MediatR.

💻 Code

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

⚠ Common mistakes

  • Mistake: Adopting MediatR by default and calling it CQRS. Why it is wrong: CQRS means separate write and read models; a mediator only dispatches requests to handlers. Teams that conflate them end up with 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.
  • Mistake: Ignoring the licence change when upgrading past 12.x. Why it is wrong: organisations over US$5M revenue need a commercial licence for v13+, and RPL's reciprocity is rarely acceptable for closed-source products. Instead: check eligibility, pin 12.x temporarily, or migrate.
  • Mistake: Handlers calling 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.
  • Mistake: Using pipeline behaviours for HTTP concerns. Why it is wrong: duplicates what endpoint filters and middleware already do. Instead: filters for HTTP, decorators for non-HTTP.
  • Mistake: Arguing about microseconds of overhead. Why it is wrong: database and network dominate. Instead: decide on readability, dependency and licence.
  • Mistake: Big-bang removal. Why it is wrong: breaks behaviour ordering and hidden notifications. Instead: adapter interface, slice-by-slice migration, tests on pipeline order.
  • Mistake: Forgetting INotification handlers during migration. Why it is wrong: side effects silently stop. Instead: inventory notifications and replace with domain event dispatch.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions pipeline behaviours or the Mediator pattern. Why: Checks pattern-level knowledge of Mediator and MediatR pipeline behaviours.
    How to 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.

  2. When: Candidate talks about vertical slices or feature folders. Why: Checks how slices are structured with or without a mediator.
    How to answer

    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.

    • Minimise coupling between slices, maximise coupling within a slice; each slice can pick its own data approach (EF Core, Dapper).
    • Cross-cutting concerns (validation, logging, transactions, authorisation) go in a pipeline: endpoint filters, middleware or decorators/behaviours.
    • Shared code is limited to genuine domain logic, not generic repositories.

    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.

  3. When: Candidate proposes decorators instead of pipeline behaviours. Why: Checks they can replace behaviours with DI decorators correctly.
    How to answer

    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.

🛠 Real-world problems: how you handle them

MediatR licence flagged by procurement during an upgrade
Situation
A [financial services] company with [~40] .NET developers upgraded packages on a [policy] API that had [~150] MediatR handlers. The upgrade pulled MediatR 13, and the licence scanner flagged RPL 1.5.
Signals
The software composition analysis tool (for example, [Dependabot/Snyk/Mend]) raised a licence-policy violation; runtime logs showed MediatR's missing-licence warning; procurement asked for a decision within [two sprints].
Investigation
Inventoried MediatR usage (handlers, behaviours, notifications) with a Roslyn-based search; checked revenue against the Community threshold; priced commercial tiers; spiked direct injection with endpoint filters on two slices and measured effort per slice.
Resolution
Immediate: pinned MediatR 12.x (Apache 2.0) to unblock releases. Long term: an ADR chose migration to an in-house `IHandler<,>` with decorators, done slice by slice over [four] sprints, with notifications replaced by domain event dispatch.
Prevention
Licence policy in CI that blocks reciprocal licences; an architecture test banning the MediatR namespace after migration; a dependency review checklist for new packages.

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.

More in Architecture Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me