Tutorials Design Patterns in C#
Mediator Pattern with MediatR — Pipeline Behaviors
Mediator Pattern with MediatR — Pipeline Behaviors: free step-by-step lesson with examples, common mistakes, and interview tips — part of Design Patterns in C# on Toolliyo Academy.
On this page
Design Patterns in C# · Lesson 36 of 69
Mediator Pattern with MediatR — Pipeline Behaviors
GoF Core ✓ → Enterprise ✓ → Cloud & Craft
Cloud & Craft · 3 — Microservices & interviews · ~6 min · Module 5: Modern Enterprise Patterns
What is this?
MediatR pipeline behaviors wrap handlers like middleware — validation, logging, transactions — without editing every handler.
Why should you care?
ShopNest wants consistent validation/logging on every command without copy-paste.
See it live — copy this example
Paste into a C# console or class library project and run dotnet run.
public interface IPipelineBehavior<TRequest, TResponse>
{
Task<TResponse> Handle(TRequest request, Func<Task<TResponse>> next);
}
public sealed class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
public async Task<TResponse> Handle(TRequest request, Func<Task<TResponse>> next)
{
Console.WriteLine($"start {typeof(TRequest).Name}");
var response = await next();
Console.WriteLine($"end {typeof(TRequest).Name}");
return response;
}
}
// mediator pipeline: logging -> validation -> handler
Console.WriteLine("pipeline: log → validate → PlaceOrderHandler");
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- Behaviors form a chain around the handler.
- This is the MediatR-specific deep dive beyond basic Send/Handle.
Practice next
- Add LoggingBehavior in a real MediatR app.
- Add ValidationBehavior throwing on invalid commands.
- Order behaviors deliberately.
- Add timing behavior with Stopwatch.
- Short-circuit validation failures.
Remember
Middleware for handlers. Cross-cutting in one place. Handlers stay pure.
ShopNest MediatR behaviors
All commands get validation + logging.
Outcome: Consistent ops without handler clutter.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!