With MediatR, what is an IPipelineBehavior<TRequest, TResponse>, and what happens when its Handle method does not call next?
answer
- a layer wrapped around the handler
- RequestHandlerDelegate<TResponse> next
- code before and after await next
- skip next: handler never runs
- AddOpenBehavior(typeof(LoggingBehavior<,>))
basics
~20 sAn 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 linesbuilder.Services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssemblyContaining<RecordRentPaymentHandler>();
cfg.AddOpenBehavior(typeof(LoggingBehavior<,>));
});go deeper
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.
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.
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.
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.