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.
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.
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();
}
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."