Pipeline Behaviors¶
Pipeline behaviors are cross-cutting middleware that wrap request handling. They form a chain similar to HTTP middleware: each behavior can run logic before and after the next handler, modify the request, short-circuit the pipeline, or handle exceptions.
graph LR
Send["mediator.send(request)"] --> B1[Behavior 1]
B1 --> B2[Behavior 2]
B2 --> Handler[Request Handler]
Handler --> B2
B2 --> B1
B1 --> Send
Defining a Behavior¶
Implement IPipelineBehavior[RequestT, ResponseT]:
Warning
Every behavior must call await next_handler(request) to continue the pipeline. Omitting
this call short-circuits the chain — the actual handler never executes.
Global Behaviors¶
Register behaviors that apply to every request via MediatorConfig:
Global behaviors execute in the order they are listed.
Per-request Behaviors¶
Attach behaviors to a specific request type via bind_request:
Execution Order¶
When a request is dispatched, behaviors execute in this order:
- Global behaviors (from
MediatorConfig.pipeline_behaviors, in order) - Per-request behaviors (from
bind_request(..., behaviors=[...]), in order) - Request handler
The response then unwinds back through the chain in reverse order.
Further reading¶
- Requests — commands, queries, and request handlers
- Events — event definitions, handlers, and publishers
- Mediator (CQRS) — setup, interfaces, and complete example