SOLID & Design Patterns Interview Question #66

What is the Mediator pattern's role in CQRS?

Advanced Patterns, CQRS & Domain-Driven Design Fundamentals Mid-Level Intermediate

Quick Interview Answer

A mediator can dispatch command and query objects to their corresponding handlers, allowing controllers or endpoints to depend on a single request-dispatch abstraction instead of many handler classes.

Detailed Explanation

A mediator can dispatch command and query objects to their corresponding handlers, allowing controllers or endpoints to depend on a single request-dispatch abstraction instead of many handler classes.

CQRS does not require a mediator. Directly injecting handlers is valid, and a mediator should be used when centralized dispatch or pipeline behavior provides enough value to justify the indirection.

Code Example

public async Task<IActionResult> Details(int id)
{
    var result = await _mediator.Send(
        new GetOrderQuery(id));

    return View(result);
}