0Pricing
C# Academy · Lesson

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 handlers

IPipelineBehavior

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

  1. CQRS Concepts
  2. Commands and Handlers with MediatR
  3. Pipeline Behaviors
  4. Notifications and Events
← Back to C# Academy