In MediatR 14, you call AddOpenBehavior for logging, validation and transaction behaviours in that order; in what order do they run around the handler?
answer
- first registered = outermost
- before-code in order, after-code reversed
- validation outside the transaction
- processors and exception behaviours sit outside yours
- TryAddEnumerable ignores duplicates
basics
~20 sMediatR 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.
solid answer
~40 sMediatR resolves `IEnumerable<IPipelineBehavior<TRequest, TResponse>>`, which the container returns in registration order, then reverses it and folds it around the handler, so index 0 is the **outermost** layer. With logging, validation, transaction registered in that order, a `RecordRentPayment` runs logging-before, validation, transaction-begin, handler, commit, then logging-after; MediatR's own tests assert exactly this outer-before, inner-before, handler, inner-after, outer-after sequence. The order is a design choice: logging outermost times and records everything, validation rejects bad commands before a transaction opens. Two subtleties in 14.2: `AddMediatR` registers its own exception and pre/post-processor behaviours before your `cfg.AddBehavior`/`AddOpenBehavior` list, so those sit outside yours, and the list is added with `TryAddEnumerable`, so calling `AddOpenBehavior` twice for one type registers it once.
code
csharp · 11 linespublic sealed class CommandTimeoutBehavior<TRequest, TResponse>
: IPipelineBehavior<TRequest, TResponse> where TRequest : notnull
{
public async Task<TResponse> Handle(TRequest request,
RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(TimeSpan.FromSeconds(10));
return await next(cts.Token); // inner behaviours and the handler see cts.Token
}
}go deeper
Recall that registration order decides nesting and that the first behaviour registered runs first on the way in and last on the way out.
Explain how MediatR reverses and folds the resolved behaviours, why logging goes outermost and validation before the transaction, and how duplicate registrations are ignored.
Account for the whole stack: processors and exception behaviours that AddMediatR places outside yours, behaviours registered directly on the container, and the token handed to next.
Treat behaviour order as part of the architecture: document it in one place, test it, and resist adding behaviours whose correctness depends on a position nobody remembers.
## The rule **First registered, outermost.** MediatR asks the container for every `IPipelineBehavior<TRequest, TResponse>`; Microsoft's container returns them in the order they were registered, open generics and closed registrations interleaved by position. MediatR reverses that list and folds it around the handler delegate, so the first behaviour wraps everything after it. For three behaviours registered A, B, C, one `Send` executes: 1. A's code before `next` 2. B's code before `next` 3. C's code before `next` 4. the handler 5. C's code after `next` 6. B's code after `next` 7. A's code after `next` MediatR's own test suite asserts this exact sequence ("Outer before", "Inner before", "Handler", "Inner after", "Outer after"). ## Choosing an order for the property-management commands ```csharp builder.Services.AddMediatR(cfg => { cfg.RegisterServicesFromAssemblyContaining<RecordRentPaymentHandler>(); cfg.AddOpenBehavior(typeof(LoggingBehavior<,>)); // outermost cfg.AddOpenBehavior(typeof(ValidationBehavior<,>)); cfg.AddOpenBehavior(typeof(TransactionBehavior<,>)); // innermost, next to the handler }); ``` | Position | Behaviour | Why there | |---|---|---| | outermost | logging / timing | sees every outcome, including validation failures and rollbacks, and times the whole pipeline | | middle | validation | rejects an invalid `RecordRentPayment` before any database work starts | | innermost | transaction | the transaction spans only the handler's work, so it stays short | Swap validation and transaction and every invalid command opens and rolls back a transaction for nothing; put logging inside validation and rejected commands never reach the log. ## The full stack `AddMediatR` builds Your list is not the whole pipeline. In 14.2, `AddMediatR` registers behaviours in this order, which is therefore the nesting from the outside in: 1. any `IPipelineBehavior<,>` you registered on the service collection **before** calling `AddMediatR`; 2. **exception behaviours**, only if the scan found implementations: `RequestExceptionActionProcessorBehavior` and `RequestExceptionProcessorBehavior` (their relative order depends on `RequestExceptionActionProcessorStrategy`); 3. **`RequestPreProcessorBehavior`**, then **`RequestPostProcessorBehavior`**, only when processors were added through `cfg.AddRequestPreProcessor` / `AddOpenRequestPreProcessor` or their post-processor counterparts; 4. your **`cfg.AddBehavior` / `cfg.AddOpenBehavior`** entries, in call order; 5. anything registered as `IPipelineBehavior<,>` **after** `AddMediatR`. Consequences: pre-processors run before your logging behaviour; post-processors run after your transaction behaviour has committed; exception handlers see exceptions thrown by your validation behaviour. In the 14.2 registrar, `AutoRegisterRequestProcessors` registers scanned processors but does not by itself add the behaviour that executes them; that behaviour is added only when the processor lists on `cfg` are non-empty, so check that auto-registered processors actually run. ## Pre- and post-processors `IRequestPreProcessor<TRequest>.Process(request, ct)` and `IRequestPostProcessor<TRequest, TResponse>.Process(request, response, ct)` are simplified behaviours with no `next`: all pre-processors run in registration order inside one behaviour before the rest of the pipeline, and all post-processors run, in order, after a successful response. A post-processor never runs when the handler throws. ## Duplicates, lifetimes and tokens - `cfg.AddOpenBehavior` entries are added with `TryAddEnumerable`, so registering the same open type twice yields one registration. Registering it again yourself with `services.AddTransient(typeof(IPipelineBehavior<,>), ...)` *after* `AddMediatR` does add a second copy, which then runs twice. - Every `Add...Behavior` overload takes an optional `ServiceLifetime`, default `Transient`. - In 14, `next` takes an optional `CancellationToken`. Passing a token (for example a linked token with a timeout) hands it to every inner layer; calling `next()` with no argument, or with `CancellationToken.None`, falls back to the token `Send` received. - Stream behaviours follow the same first-registered-outermost rule, in their own list (`AddStreamBehavior`, `AddOpenStreamBehavior`). ## Pinning the order in a test Order is easy to break with an innocent-looking edit to `Program.cs`, so pin it. Build the real service collection, resolve `IEnumerable<IPipelineBehavior<RecordRentPayment, PaymentReceipt>>` from it, and assert the sequence of concrete types: that list, first to last, is the nesting from the outside in. The test also catches a behaviour that silently stopped applying to a request type because a generic constraint no longer matches, which no compiler warning reports.
- Where do MediatR pre- and post-processors run relative to your own behaviours?Outside them. `AddMediatR` registers `RequestPreProcessorBehavior` and `RequestPostProcessorBehavior` before your `cfg.AddBehavior`/`AddOpenBehavior` entries, so pre-processors run before your outermost behaviour and post-processors run after your innermost one has returned, after a transaction behaviour has committed. Each runs its processors in registration order, and post-processors are skipped when the handler throws.
- You add the same open behaviour twice by accident. Does it run twice?Not if both registrations go through `cfg.AddOpenBehavior`: `AddMediatR` adds that list with `TryAddEnumerable`, which skips an identical service-and-implementation pair. A copy you register yourself with `services.AddTransient(typeof(IPipelineBehavior<,>), ...)` after `AddMediatR` is a separate descriptor, and that one does run twice.
- How can a MediatR 14 behaviour give the rest of the pipeline a different CancellationToken?Pass it to the delegate: `RequestHandlerDelegate<TResponse>` takes an optional `CancellationToken`, and MediatR forwards it to inner behaviours and the handler, for example a linked token with `CancelAfter` for a timeout. Calling `next()` without a token, or with `CancellationToken.None`, falls back to the token `Send` received, so you cannot strip cancellation that way.
Behaviours are like the security layers of an apartment building: the first one registered is the street door, the next the lobby desk, the last the flat's own lock. A visitor passes them from the outside in, and on the way out leaves through the flat door first and the street door last.
- The last behaviour registered with AddOpenBehavior runs first.
- MediatR orders behaviours alphabetically by class name.
- Your AddOpenBehavior behaviours always run outside the pre-processors.
- Calling cfg.AddOpenBehavior twice for one type makes it run twice.
- Passing CancellationToken.None to next removes cancellation for the handler.
Assumes MediatR 14.2: the first behaviour registered is outermost, AddMediatR adds its exception and processor behaviours ahead of cfg's behaviours, and RequestHandlerDelegate takes an optional CancellationToken.