Monday, 22 September 2025

MediatR

 What is MediatR?

  • MediatR is a lightweight mediator library for .NET.

  • It acts like a post office:

    • Your code sends a request (letter).

    • MediatR delivers it to the correct handler (person who processes that letter).

  • This removes the need for direct references between classes.

In short: No more “Controller calls Service calls Repository directly.”
Instead: Controller sends a message → MediatR finds the right handler.


2️⃣ Why Use MediatR?

  • Loose Coupling: Request sender doesn’t know who handles it.

  • 📦 Clean Architecture Fit: Keeps layers independent.

  • 🧩 Supports Patterns: Perfect for CQRS (separate Command & Query handlers).

  • 🧪 Easy Testing: Handlers are single-purpose classes.


3️⃣ Key Concepts

TermMeaning
RequestThe message you send (Command or Query).
HandlerClass that processes the request.
NotificationOne-to-many broadcast message (like events).

4️⃣ Basic Example

Install NuGet Package

dotnet add package MediatR dotnet add package MediatR.Extensions.Microsoft.DependencyInjection

Step A: Create a Request (Command or Query)

public record Ping(string Message) : IRequest<string>;
  • IRequest<TResponse> = a request that expects a response.

Step B: Create a Handler

public class PingHandler : IRequestHandler<Ping, string> { public Task<string> Handle(Ping request, CancellationToken cancellationToken) { return Task.FromResult($"Pong: {request.Message}"); } }

Step C: Register MediatR in Program.cs

builder.Services.AddMediatR(typeof(Program));

Step D: Use It in a Controller or Service

public class TestController : ControllerBase { private readonly IMediator _mediator; public TestController(IMediator mediator) => _mediator = mediator; [HttpGet("ping")] public async Task<string> Ping(string msg) { return await _mediator.Send(new Ping(msg)); } }
  • Send() delivers the request to the matching handler.


5️⃣ Notifications (Publish/Subscribe)

  • For broadcasting events to many handlers.

Notification class:

public record OrderPlaced(int OrderId) : INotification;

Handlers:

public class EmailHandler : INotificationHandler<OrderPlaced> { ... } public class SmsHandler : INotificationHandler<OrderPlaced> { ... }

Publishing:

await _mediator.Publish(new OrderPlaced(orderId));

Both handlers run independently.


6️⃣ Common Uses in .NET

  • CQRS: Separate Command and Query handlers.

  • Domain Events: Publish events like UserRegistered.

  • Decoupling: Replace direct service calls.


7️⃣ Benefits Recap

  • ✅ Cleaner, more maintainable code.

  • ✅ Easy unit testing of each handler.

  • ✅ Scales well as app grows.


Summary:
MediatR is a mediator pattern implementation for .NET.
It lets you send commands/queries and publish notifications without tight coupling.
Perfect for Clean Architecture + CQRS projects.