| nopCommerce-QA :👈 | 👉:OpenTelemetry in .NET |
MediatR in .NET |
Mediator Pattern in .NET
1. What is the Mediator Pattern?
The Mediator Pattern is a behavioral design pattern that allows different objects or components to communicate with each other through a central object called a Mediator, instead of communicating directly with one another.
In simple words, Mediator acts as a middleman between different components and manages communication between them.
Real-World Example – Airport
Imagine an airport where multiple aircraft need permission to take off and land.
- Aircraft do not communicate directly with every other aircraft.
- Instead, they communicate through the Air Traffic Controller.
- The Air Traffic Controller coordinates all aircraft movements.
Here:
- Aircraft: Objects or components.
- Air Traffic Controller: Mediator.
- Communication: Mediator Pattern.
Mediator Pattern – SVG Diagram
2. Why Do We Need the Mediator Pattern?
Consider an e-commerce application.
When a customer places an order, several operations need to happen:
- Validate the order.
- Check product availability.
- Calculate the total price.
- Process payment.
- Update inventory.
- Send an email notification.
Without Mediator – Tightly Coupled Architecture
Without the Mediator Pattern, OrderService might directly communicate with multiple services.
Problems with This Approach
- OrderService depends on multiple services.
- Adding a new operation requires modifying OrderService.
- Unit testing becomes more complicated.
- Dependencies increase as the application grows.
- Business workflows become tightly coupled.
With Mediator – Loosely Coupled Architecture
Instead of directly communicating with multiple services, OrderService sends a request to the Mediator.
The Mediator identifies the appropriate handler, which executes the required business logic.
3. What is MediatR in .NET?
MediatR is a third-party .NET library that implements the Mediator Pattern.
It provides a convenient way to send requests to their corresponding handlers without directly depending on those handlers.
Important MediatR concepts:
| Component | Purpose |
|---|---|
| ISender | Sends requests to handlers. |
| IMediator | Provides request sending and notification publishing capabilities. |
| IRequest | Represents a request. |
| IRequestHandler | Processes a request. |
| INotification | Represents a notification event. |
| INotificationHandler | Handles notification events. |
| IPipelineBehavior | Executes common logic around request handlers. |
Note: ICommand and IQuery are commonly created as application-level abstractions. They are not mandatory MediatR interfaces.
4. How Mediator Works in ASP.NET Core
Consider an ASP.NET Core Web API that creates a customer.
Execution Flow
Step-by-step execution:
- Customer sends an HTTP request.
- Controller creates a CreateCustomerCommand.
- Controller sends the command using Mediator.
- MediatR identifies the corresponding handler.
- Handler executes business logic.
- Handler saves the customer using a repository.
- Handler returns the result.
- Controller sends an HTTP response.
5. Step-by-Step Implementation in ASP.NET Core
Let's implement a simple example: Creating a customer using MediatR.
Step 1: Install MediatR
dotnet add package MediatR
Step 2: Register MediatR in Program.cs
using MediatR;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddMediatR(cfg =>
cfg.RegisterServicesFromAssembly(
typeof(Program).Assembly));
var app = builder.Build();
app.MapControllers();
app.Run();
This registers MediatR and discovers request handlers in the specified assembly.
Step 3: Create Customer Model
Customer.cs
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
Step 4: Create a Command
CreateCustomerCommand.cs
using MediatR;
public class CreateCustomerCommand : IRequest<int>
{
public string Name { get; set; }
public string Email { get; set; }
}
Explanation:
- IRequest<int> means this request expects an integer response.
- The integer represents the newly created customer ID.
- The command contains the data required to create a customer.
Step 5: Create a Command Handler
CreateCustomerHandler.cs
using MediatR;
public class CreateCustomerHandler :
IRequestHandler<CreateCustomerCommand, int>
{
public async Task<int> Handle(
CreateCustomerCommand request,
CancellationToken cancellationToken)
{
var customer = new Customer
{
Id = 101,
Name = request.Name,
Email = request.Email
};
// Save customer to database
return customer.Id;
}
}
Explanation:
- IRequestHandler identifies this class as the handler.
- Handle() executes business logic.
- request contains the incoming command data.
- CancellationToken supports operation cancellation.
- The method returns the newly created customer ID.
The hardcoded ID is only for demonstration. A real application should save the customer through a database repository.
Step 6: Call Mediator from Controller
CustomerController.cs
using MediatR;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/customers")]
public class CustomerController : ControllerBase
{
private readonly ISender _sender;
public CustomerController(ISender sender)
{
_sender = sender;
}
[HttpPost]
public async Task<IActionResult> Create(
CreateCustomerCommand command)
{
var customerId =
await _sender.Send(command);
return Ok(customerId);
}
}
Important: The controller does not know anything about CreateCustomerHandler. It only knows about ISender.
MediatR finds the appropriate handler and executes it.
6. What are Commands and Queries?
Applications commonly use Mediator together with CQRS-style separation.
CQRS stands for Command Query Responsibility Segregation.
It separates operations into two categories.
A. Command
A command changes the application state.
Examples:
- CreateCustomer
- UpdateCustomer
- DeleteCustomer
- PlaceOrder
- CancelOrder
Example:
public class UpdateCustomerCommand : IRequest<bool>
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
B. Query
A query retrieves information without changing application state.
Examples:
- GetCustomerById
- GetAllCustomers
- GetOrders
- GetProductDetails
Example:
public class GetCustomerQuery : IRequest<Customer>
{
public int Id { get; set; }
}
Query Handler
public class GetCustomerHandler :
IRequestHandler<GetCustomerQuery, Customer>
{
public async Task<Customer> Handle(
GetCustomerQuery request,
CancellationToken cancellationToken)
{
// Retrieve customer from database
return new Customer
{
Id = request.Id,
Name = "John",
Email = "john@example.com"
};
}
}
Command vs Query – SVG Diagram
| Feature | Command | Query |
|---|---|---|
| Purpose | Changes data | Retrieves data |
| Database | Usually INSERT, UPDATE, DELETE | Usually SELECT |
| Return value | ID, status or result | Requested data |
| Example | CreateOrder | GetOrderById |
| State change | Yes | No |
7. What are Notifications in MediatR?
Sometimes one operation needs to notify multiple components.
For example, after an order is created:
- Send an email.
- Update inventory.
- Send a notification.
- Record an audit entry.
Instead of calling each service directly, we can publish a notification.
Step 1: Create Notification
using MediatR;
public class OrderCreatedNotification : INotification
{
public int OrderId { get; set; }
}
Step 2: Create Email Notification Handler
using MediatR;
public class EmailNotificationHandler :
INotificationHandler<OrderCreatedNotification>
{
public Task Handle(
OrderCreatedNotification notification,
CancellationToken cancellationToken)
{
Console.WriteLine(
"Order confirmation email sent.");
return Task.CompletedTask;
}
}
Step 3: Create Inventory Notification Handler
using MediatR;
public class InventoryNotificationHandler :
INotificationHandler<OrderCreatedNotification>
{
public Task Handle(
OrderCreatedNotification notification,
CancellationToken cancellationToken)
{
Console.WriteLine("Inventory updated.");
return Task.CompletedTask;
}
}
Step 4: Publish Notification
await _sender.Publish(
new OrderCreatedNotification
{
OrderId = 101
});
MediatR invokes all registered handlers for this notification.
Notification Flow – SVG Diagram
Important: MediatR notifications are in-process notifications. They are not automatically durable or distributed messages. For reliable background processing across services, consider RabbitMQ or Azure Service Bus.
8. What is Pipeline Behavior?
Pipeline Behavior is another important MediatR feature.
It allows you to execute common logic before and after a request handler.
Typical use cases:
- Logging
- Validation
- Performance monitoring
- Authorization
- Transaction management
Example – Logging Behavior
using MediatR;
public class LoggingBehavior<TRequest, TResponse>
: IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
Console.WriteLine("Before Handler");
var response = await next();
Console.WriteLine("After Handler");
return response;
}
}
Register Pipeline Behavior
builder.Services.AddTransient(
typeof(IPipelineBehavior<,>),
typeof(LoggingBehavior<,>));
Pipeline Execution – SVG Diagram
The order of behaviors depends on their registration and pipeline configuration.
9. Mediator vs Dependency Injection
These two concepts are related but different.
| Dependency Injection | Mediator |
|---|---|
| Provides dependencies to classes. | Coordinates request handling. |
| Manages object dependencies. | Routes requests to handlers. |
| Reduces object creation coupling. | Reduces direct communication coupling. |
| Example: Inject ICustomerService. | Example: Send GetCustomerQuery. |
You can use Dependency Injection and Mediator together. MediatR itself uses Dependency Injection to resolve handlers.
10. Mediator vs Observer Pattern
| Mediator | Observer |
|---|---|
| Central object coordinates communication. | One object notifies subscribers. |
| Requests are routed to handlers. | Events are broadcast to observers. |
| Often used for request handling. | Often used for event notifications. |
| Example: MediatR.Send(). | Example: Event subscription. |
11. Advantages of Mediator Pattern
- Reduces tight coupling between components.
- Improves separation of concerns.
- Makes code easier to maintain.
- Improves unit testing.
- Supports CQRS-style architecture.
- Centralizes request handling.
- Supports reusable cross-cutting logic through pipeline behaviors.
- Makes large applications easier to organize.
12. Disadvantages of Mediator Pattern
- Introduces additional classes such as commands, queries and handlers.
- Can increase code complexity in small applications.
- Debugging request flow may require navigating multiple classes.
- Excessive use can create unnecessary abstractions.
- A large number of handlers can make project organization difficult.
- MediatR introduces an additional library dependency.
13. When Should You Use Mediator?
Use Mediator When:
- Building medium or large ASP.NET Core applications.
- Implementing CQRS.
- Developing complex business workflows.
- Multiple components need coordinated request handling.
- You want to separate controllers from business logic.
- You need common validation, logging or transaction behaviors.
Avoid Introducing It Unnecessarily When:
- Building a very small CRUD application.
- A simple service method is sufficient.
- The abstraction adds more complexity than value.
14. Mediator in Microservices Architecture
Mediator is commonly used inside individual microservices.
Example Architecture
Important distinction:
- MediatR handles communication inside an application process.
- RabbitMQ or Azure Service Bus handles message communication between separate services.
- They solve different problems and can be used together.
15. Frequently Asked .NET Interview Questions
Q1. What is the Mediator Pattern?
It is a behavioral design pattern that centralizes communication between objects through a mediator instead of allowing direct communication.
Q2. What is MediatR?
MediatR is a .NET library that implements the Mediator Pattern and provides request-response and notification handling.
Q3. What is IRequest?
IRequest represents a request that can be sent through the mediator. It can optionally define a response type.
Q4. What is IRequestHandler?
It defines the handler responsible for processing a particular request.
Q5. What is the difference between Send() and Publish()?
- Send(): Sends one request to its corresponding request handler.
- Publish(): Publishes a notification to its registered notification handlers.
Q6. What is IPipelineBehavior?
It allows common logic such as logging, validation and performance monitoring to execute around request handlers.
Q7. Can multiple handlers handle one request?
Normally, a request has one corresponding request handler. Multiple handlers can handle the same notification.
Q8. Is MediatR part of ASP.NET Core?
No. MediatR is a third-party .NET library.
Q9. Is Mediator the same as CQRS?
No. Mediator is a communication pattern. CQRS separates commands that change state from queries that retrieve data. They are often used together.
Q10. Is MediatR a replacement for Dependency Injection?
No. MediatR works with Dependency Injection; it does not replace it.
16. Final Summary
| Concept | Meaning |
|---|---|
| Mediator Pattern | Centralizes communication between objects. |
| MediatR | .NET library implementing the pattern. |
| IRequest | Represents a request. |
| IRequestHandler | Processes a request. |
| Send() | Sends a request to one handler. |
| INotification | Represents a notification event. |
| Publish() | Publishes a notification. |
| INotificationHandler | Handles a notification. |
| IPipelineBehavior | Executes logic around request handling. |
| CQRS | Separates commands and queries. |
17. Recommended Learning Path
For ASP.NET Core development, learn these concepts in the following order:
- Dependency Injection
- Repository Pattern
- Mediator Pattern
- MediatR Implementation
- CQRS Architecture
- FluentValidation with MediatR
- Pipeline Behaviors
- Clean Architecture
- Domain Events
- RabbitMQ and Azure Service Bus
Professional Tip: Learn how Mediator, CQRS, Repository Pattern, Dependency Injection and Clean Architecture work together. These concepts are particularly useful when developing enterprise ASP.NET Core applications and microservices.
| nopCommerce-QA :👈 | 👉:OpenTelemetry in .NET |