Pipeline Behaviors
Add cross-cutting logic with behaviors.
Cross-Cutting Concerns
Logging, validation, timing and transactions apply to many handlers. Copying that code into each handler is repetitive and error-prone.
MediatR's pipeline behaviors let you wrap every request with shared logic.
// One behavior runs around all handlersIPipelineBehavior
A behavior implements IPipelineBehavior<TRequest, TResponse>. Its Handle method receives the request and a next delegate that invokes the rest of the pipeline.
public class LoggingBehavior<TRequest, TResponse>
: IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken ct)
{
// before
var response = await next();
// after
return response;
}
}All lessons in this course
- CQRS Concepts
- Commands and Handlers with MediatR
- Pipeline Behaviors
- Notifications and Events