skip to content

MediatR

MediatR dispatches requests to one handler and notifications to many, wrapped in pipeline behaviors; it is now dual-licensed with a paid key. Interviewers ask if its indirection earns its keep.

on this pageshow

explore

questions

12

With MediatR, what is an IPipelineBehavior<TRequest, TResponse>, and what happens when its Handle method does not call next?

level: juniorimportance: must knowfreq 60%

answer

  1. a layer wrapped around the handler
  2. RequestHandlerDelegate<TResponse> next
  3. code before and after await next
  4. skip next: handler never runs
  5. AddOpenBehavior(typeof(LoggingBehavior<,>))

basics

~20 s

An IPipelineBehavior wraps each matching Send: Handle gets the request and a RequestHandlerDelegate next, runs code around awaiting it, and returns the response. If it skips next, neither the handler nor inner behaviours run, and its own return value is the response.

solid answer

~40 s

`IPipelineBehavior<TRequest, TResponse>` is MediatR's around-advice for requests. Its `Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)` can run code, `await next(cancellationToken)` to continue to the next behaviour and finally the handler, inspect the response, and return it. Not calling `next` short-circuits: inner behaviours and the handler never run, and whatever the behaviour returns (a cached value, say) is what `Send` returns; throwing does the same with an exception. Behaviours wrap `Send` only, not `Publish`, and streams have their own interface. They are not found by the assembly scan: register them with `cfg.AddOpenBehavior(typeof(LoggingBehavior<,>))` for every request, or `cfg.AddBehavior<T>()` for a closed one. Both default to transient, so a fresh behaviour is resolved per `Send`.

code

csharp · 5 lines
csharp
builder.Services.AddMediatR(cfg =>
{
    cfg.RegisterServicesFromAssemblyContaining<RecordRentPaymentHandler>();
    cfg.AddOpenBehavior(typeof(LoggingBehavior<,>));
});

go deeper

for a junior

Recall the shape: a behaviour receives the request and next, does work before and after awaiting next, and returns the response. Know that it is registered with AddOpenBehavior.

for a middle

Explain how MediatR folds behaviours into nested delegates, what short-circuiting by returning or throwing does, and why behaviours apply to Send but not to Publish or streams.

for a senior

Show judgement about what belongs in a behaviour: request-level concerns such as validation, transactions and caching, never HTTP shaping, and no accidental double execution of next.

for a principal

Weigh behaviours against a plain decorator or framework filters: a behaviour applies to every request silently, which is powerful and also hides behaviour from whoever reads one handler.

## What a behaviour is A MediatR **pipeline behaviour** is a class that sits between `ISender.Send` and the request handler. Every behaviour that applies to a request type wraps the next one, and the innermost wraps the handler, so a single `Send` travels inward through the layers and the response travels back out. It is MediatR's place for cross-cutting work that concerns the *request object* rather than HTTP: logging, timing, validation, transactions, caching, auditing. The contract, in MediatR 14: - **`IPipelineBehavior<in TRequest, TResponse> where TRequest : notnull`** - **`Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)`** - **`delegate Task<TResponse> RequestHandlerDelegate<TResponse>(CancellationToken t = default)`**: calling it runs *the rest of the pipeline*. A request with no result still goes through behaviours; its `TResponse` is MediatR's `Unit` struct. ## What `next` really is When you `Send`, MediatR resolves every `IPipelineBehavior<TRequest, TResponse>` from the container, reverses the list, and folds it around a delegate that resolves and calls the handler. The result is a chain of closures: behaviour 1's `next` calls behaviour 2's `Handle`, whose `next` calls the handler. Therefore: 1. Code **before** `await next(...)` runs on the way in, in registration order. 2. Code **after** it runs on the way out, in reverse order, and can read or replace the response. 3. A behaviour that **does not call `next`** ends the journey there. The handler is never resolved, and the behaviour's return value is the response. 4. A behaviour that **throws** before `next` also stops it; the exception goes back out through the outer behaviours to the caller. 5. A behaviour that **calls `next` twice** runs everything inside it twice, handler included. ## A logging behaviour for the property-management app ```csharp 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 cancellationToken) { var started = Stopwatch.GetTimestamp(); var response = await next(cancellationToken); logger.LogInformation("{Request} handled in {Elapsed} ms", typeof(TRequest).Name, Stopwatch.GetElapsedTime(started).TotalMilliseconds); return response; } } ``` Registered once with `cfg.AddOpenBehavior(typeof(LoggingBehavior<,>))`, it wraps `RecordRentPayment`, `ScheduleMaintenanceVisit`, `RenewLease` and every other request the API sends. ## Short-circuiting on purpose | Goal | How the behaviour ends early | |---|---| | Serve a cached query result | return the cached `TResponse` without calling `next` | | Reject an invalid command | throw (for example a validation exception) before `next` | | Enforce a business-level permission | throw an authorization exception of your own | | Feature-flag a command off | return a "disabled" response, if `TResponse` can express it | The behaviour must return a `TResponse`, so it cannot invent an HTTP result for an arbitrary request; turning an exception into a status code is the web layer's job. ## Registration and scope - **Not scanned.** `RegisterServicesFromAssembly...` registers handlers, never behaviours, so their order stays explicit. - **`AddOpenBehavior(Type)`** registers an open generic such as `LoggingBehavior<,>` for every request; **`AddBehavior<TImplementation>()`** registers a closed behaviour against the `IPipelineBehavior<,>` interfaces it implements. Either throws `InvalidOperationException` if the type does not implement `IPipelineBehavior<,>`. - **Lifetime.** Both take an optional `ServiceLifetime`, default `Transient`; a behaviour with constructor dependencies is resolved fresh for each `Send`. - **Only `Send`.** `Publish` sends notifications straight to their handlers through the notification publisher. `CreateStream` uses `IStreamPipelineBehavior<TRequest, TResponse>`, whose `next` is a `StreamHandlerDelegate<TResponse>` that takes no token, registered with `AddStreamBehavior` or `AddOpenStreamBehavior`. ## Testing a behaviour on its own Because `next` is just a delegate, a behaviour needs no mediator to test. Construct it directly and pass a lambda that stands in for the rest of the pipeline: - assert that the lambda was invoked exactly once on the happy path; - assert that it was **not** invoked when the behaviour should short-circuit (a cache hit, an invalid command); - assert that the response the lambda returns is the one the behaviour returns, unless the behaviour is meant to replace it. A lambda such as `_ => Task.FromResult(receipt)` satisfies `RequestHandlerDelegate<PaymentReceipt>`, since the delegate's single parameter is the optional token. One integration test through a real container then proves the registration and the order.

  • Does a MediatR pipeline behaviour run for Publish or CreateStream?
    No. `IPipelineBehavior<TRequest, TResponse>` wraps `Send` only. Notifications go straight to their handlers through the notification publisher. Streams have their own `IStreamPipelineBehavior<TRequest, TResponse>`, whose `next` is a `StreamHandlerDelegate<TResponse>` with no token parameter, registered with `AddStreamBehavior` or `AddOpenStreamBehavior`.
  • What happens if a MediatR behaviour calls next twice?
    The delegate runs the rest of the pipeline again: inner behaviours run a second time and the handler is resolved and executed again, so a command such as `RecordRentPayment` would record two payments. Only a deliberate retry behaviour should do that, and then the handler must be safe to re-run.
  • Why does RegisterServicesFromAssemblyContaining not pick up your behaviours?
    The scan registers request, notification and stream handlers plus exception handlers and actions, but never `IPipelineBehavior` implementations. Behaviours are registered explicitly with `AddBehavior` or `AddOpenBehavior` (or directly as `IPipelineBehavior<,>` services) because their registration order decides their nesting.

  • Behaviours are discovered automatically by the AddMediatR assembly scan.
  • A pipeline behaviour also runs for notifications sent with Publish.
  • If a behaviour forgets to call next, MediatR calls the handler anyway.
  • Behaviours are singletons shared by every request by default.
  • Calling next twice is harmless because MediatR caches the handler's response.
open as a page

With MediatR, how does ISender.Send differ from IPublisher.Publish, and how many handlers does each one expect?

level: juniorimportance: must knowfreq 72%

basics

~20 s

MediatR's Send delivers an IRequest<TResponse> to exactly one IRequestHandler and returns its response; Publish delivers an INotification to every registered INotificationHandler, possibly none, and returns a plain Task. ISender exposes Send, IPublisher exposes Publish, IMediator both.

open as a page

In MediatR 14, you call AddOpenBehavior for logging, validation and transaction behaviours in that order; in what order do they run around the handler?

level: middleimportance: must knowfreq 55%

basics

~20 s

MediatR nests behaviours in registration order, the first registered outermost. Logging starts first and finishes last, validation runs inside it, the transaction inside that, and the handler in the middle; the after-code unwinds in reverse.

open as a page

With MediatR's default notification publisher, what happens when one of three OrderPlaced handlers throws, and how does TaskWhenAllPublisher change that?

level: seniorimportance: must knowfreq 58%

basics

~20 s

With the default ForeachAwaitPublisher, handlers run one after another; the first exception stops the remaining handlers and propagates out of Publish. TaskWhenAllPublisher starts every handler, so all of them run, and Publish then faults with their failures.

open as a page

With MediatR, how do you write a validation behaviour that runs every FluentValidation IValidator<TRequest> before the handler, and what are its traps?

level: middleimportance: should knowfreq 52%

basics

~20 s

A ValidationBehavior<TRequest, TResponse> injects IEnumerable<IValidator<TRequest>>, runs each validator's ValidateAsync before calling next, and throws FluentValidation's ValidationException when any failure exists, so handlers only see valid requests. The web layer turns that exception into a 400.

open as a page

With MediatR in an ASP.NET Core API, how does an IPipelineBehavior differ from middleware and a Minimal API endpoint filter, and when do you choose each?

level: middleimportance: should knowfreq 48%

basics

~20 s

Middleware sees every HTTP request as an HttpContext; an endpoint filter wraps chosen endpoints and sees bound arguments; a MediatR behaviour wraps each Send with the typed request, whoever sends it. Choose by what the concern must see and who calls.

open as a page

In MediatR 14, what does AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<Program>()) register, with which lifetimes, and when does it throw?

level: middleimportance: should knowfreq 50%

basics

~10 s

AddMediatR scans the assemblies you name for request, notification and stream handlers, registers them as transient, and adds IMediator, ISender and IPublisher at cfg.Lifetime, Transient by default. Called without any assembly, it throws ArgumentException.

open as a page

With MediatR and EF Core, how would you write a transaction behaviour for commands, and what breaks with nested Send calls, notifications and a retrying execution strategy?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Constrain it to a command marker, begin a transaction on the request's DbContext, await next, commit; disposal rolls back on failure. Guard nested Send with CurrentTransaction, defer side effects until after commit, and run it inside the execution strategy.

open as a page

In MediatR 14, where does the Lucky Penny licence key come from, and what happens at runtime when it is missing, invalid or expired?

level: seniorimportance: should knowfreq 40%

basics

~10 s

MediatR 14 reads the key from cfg.LicenseKey or Mediator.LicenseKey, then MEDIATR_LICENSE_KEY, then LUCKYPENNY_LICENSE_KEY. A missing, invalid or expired key never disables anything: MediatR only writes log entries under the LuckyPennySoftware.MediatR.License category.

open as a page

After MediatR moved to Lucky Penny's RPL-1.5-or-commercial licence, how would you decide whether a portfolio of ASP.NET Core services licenses it or replaces it?

level: principalimportance: should knowfreq 30%

basics

~20 s

Treat it as a licensing decision, not a code fix: MediatR 14 ships under RPL 1.5 or a paid Lucky Penny licence and only logs licence problems. Inventory what each service uses, then weigh licence cost against replacement effort.

open as a page

With MediatR, how do IStreamRequest<T> and ISender.CreateStream work, and when would you use them instead of an IRequest<List<T>>?

level: middleimportance: nice to knowfreq 20%

basics

~20 s

An IStreamRequest<T> is handled by one IStreamRequestHandler whose Handle returns IAsyncEnumerable<T>; ISender.CreateStream returns that sequence, and items flow as the handler yields them. Use it when results are large or arrive over time, instead of buffering a List<T>.

open as a page

With MediatR, how do IRequestExceptionHandler and IRequestExceptionAction differ, and in which order and for which exceptions do they run?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

An IRequestExceptionHandler can turn an exception into a response with state.SetHandled(response); an IRequestExceptionAction only reacts, then the exception is rethrown. Both match from the most specific exception type up, and by default actions see only unhandled exceptions.

open as a page