Tutorials Design Patterns Mastery

Mediator Pattern: Decoupling components with MediatR

On this page

The Mediator Pattern

The Mediator Pattern defines an object that encapsulates how a set of objects interact. It promotes loose coupling by keeping objects from referring to each other explicitly, allowing you to vary their interaction independently.

1. Solving the "Spaghetti" Problem

If 10 objects all need to talk to each other, you have 90 direct connections. This is spaghetti code. With a Mediator, all 10 objects talk ONLY to the Mediator. The Mediator decides who else needs to know.

2. Industry Standard: MediatR

In modern .NET architecture, we use the MediatR library. Instead of a Controller calling a Service, which calls a Repository, the Controller sends a "Request" into the Mediator bus. Some Handler somewhere in the app picks it up.

// Controller
public async Task<IActionResult> Create(CreateUserCommand command) 
{
    // The controller has NO IDEA who handles this!
    await _mediator.Send(command); 
    return Ok();
}

4. Interview Mastery

Q: "What are the pros and cons of using MediatR in an ASP.NET Core project?"

Architect Answer: "The **Pros** are maximum decoupling and easier unit testing. Each hander is a tiny, isolated slice of logic. It also supports 'Pipeline Behaviors' for global logging and validation. The **Cons** are 'Invisible Logic.' Since there is no direct method call, you can't just Ctrl+Click to see where the request goes. It makes debugging more difficult for juniors because the flow of the application becomes abstract."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Design Patterns Mastery
Course syllabus
1. Introduction to Design Patterns
2. Creational Patterns
3. Structural Patterns
4. Behavioral Patterns
5. Modern Enterprise & Cloud Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details