---
title: "What is MediatR and how does it relate to Clean Architecture?"  
description: "What is MediatR and how does it relate to Clean Architecture?"  
author: "Ravi Vishwakarma"  
published: 2025-06-16  
updated: 2025-06-16  
canonical: https://www.mindstick.com/interview/34249/what-is-mediatr-and-how-does-it-relate-to-clean-architecture  
category: "c#"  
tags: ["c#"]  
reading_time: 5 minutes  

---

# What is MediatR and how does it relate to Clean Architecture?

### 🧭 What is MediatR?

**MediatR** is a simple and lightweight **.NET library** that implements the **Mediator Pattern**, which helps reduce **tight coupling** between components by centralizing communication.

In MediatR:

- **Requests** (Commands or Queries) are sent to a **mediator** instead of calling services or logic directly.
- The **mediator** then invokes the appropriate **handler**.

## NuGet Package:

```plaintext
Install-Package MediatR.Extensions.Microsoft.DependencyInjection
```

### Basic MediatR Flow

```plaintext
Controller → MediatR.Send(request) → Handler → Business Logic → Response
```

### Example

#### 1. Define a Command (write action)

```cs
public record CreateStudentCommand(string Name, string Email) : IRequest<bool>;
```

#### 2. Define a Handler

```cs
public class CreateStudentHandler : IRequestHandler<CreateStudentCommand, bool>
{
    private readonly AppDbContext _db;
    public CreateStudentHandler(AppDbContext db) => _db = db;

    public async Task<bool> Handle(CreateStudentCommand request, CancellationToken ct)
    {
        _db.Students.Add(new Student { Name = request.Name, Email = request.Email });
        await _db.SaveChangesAsync();
        return true;
    }
}
```

#### 3. Send from Controller

```cs
public class StudentsController : ControllerBase
{
    private readonly IMediator _mediator;
    public StudentsController(IMediator mediator) => _mediator = mediator;

    [HttpPost]
    public async Task<IActionResult> CreateStudent(CreateStudentCommand command)
    {
        var result = await _mediator.Send(command);
        return Ok(result);
    }
}
```

### MediatR + Clean Architecture

**Clean Architecture** separates the system into layers:

```plaintext
[ Presentation ]
[ Application  ] ← Business rules (Application layer, UseCases)
[ Domain       ] ← Core business models/rules
[ Infrastructure ] ← EF Core, Email, External APIs, etc.
```

#### How MediatR Fits In:

| Clean Architecture Layer | Role of MediatR |
| --- | --- |
| **Application Layer** | Hosts MediatR requests and handlers (CQRS) |
| **Presentation Layer** | Sends requests via `IMediator.Send(...)` |
| **Infrastructure** | Injected dependencies consumed by handlers |

#### Benefits:

- Encourages **Single Responsibility** per handler
- Keeps **Controllers thin**
- Promotes **decoupling** of business logic from delivery (controller/UI)
- Facilitates **unit testing** of handlers
- Natural fit for **CQRS** (Command Query Responsibility Segregation)

### CQRS + MediatR + Clean Architecture (Typical Pattern)

```plaintext
[ API Controller ]
        ↓
[ IMediator.Send() ]
        ↓
[ Command / Query Handler ]
        ↓
[ Application Services / Repositories ]
```

### Summary

| Aspect | MediatR |
| --- | --- |
| Pattern | Mediator |
| Used for | Decoupling request handling |
| Works well with | Clean Architecture & CQRS |
| Pros | Decouples logic, testable, modular |
| Common Use | Handle Commands & Queries |

## Answers

### Answer by Ravi Vishwakarma

### 🧭 What is MediatR?

**MediatR** is a simple and lightweight **.NET library** that implements the **Mediator Pattern**, which helps reduce **tight coupling** between components by centralizing communication.

In MediatR:

- **Requests** (Commands or Queries) are sent to a **mediator** instead of calling services or logic directly.
- The **mediator** then invokes the appropriate **handler**.

## NuGet Package:

```plaintext
Install-Package MediatR.Extensions.Microsoft.DependencyInjection
```

### Basic MediatR Flow

```plaintext
Controller → MediatR.Send(request) → Handler → Business Logic → Response
```

### Example

#### 1. Define a Command (write action)

```cs
public record CreateStudentCommand(string Name, string Email) : IRequest<bool>;
```

#### 2. Define a Handler

```cs
public class CreateStudentHandler : IRequestHandler<CreateStudentCommand, bool>
{
    private readonly AppDbContext _db;
    public CreateStudentHandler(AppDbContext db) => _db = db;

    public async Task<bool> Handle(CreateStudentCommand request, CancellationToken ct)
    {
        _db.Students.Add(new Student { Name = request.Name, Email = request.Email });
        await _db.SaveChangesAsync();
        return true;
    }
}
```

#### 3. Send from Controller

```cs
public class StudentsController : ControllerBase
{
    private readonly IMediator _mediator;
    public StudentsController(IMediator mediator) => _mediator = mediator;

    [HttpPost]
    public async Task<IActionResult> CreateStudent(CreateStudentCommand command)
    {
        var result = await _mediator.Send(command);
        return Ok(result);
    }
}
```

### MediatR + Clean Architecture

**Clean Architecture** separates the system into layers:

```plaintext
[ Presentation ]
[ Application  ] ← Business rules (Application layer, UseCases)
[ Domain       ] ← Core business models/rules
[ Infrastructure ] ← EF Core, Email, External APIs, etc.
```

#### How MediatR Fits In:

| Clean Architecture Layer | Role of MediatR |
| --- | --- |
| **Application Layer** | Hosts MediatR requests and handlers (CQRS) |
| **Presentation Layer** | Sends requests via `IMediator.Send(...)` |
| **Infrastructure** | Injected dependencies consumed by handlers |

#### Benefits:

- Encourages **Single Responsibility** per handler
- Keeps **Controllers thin**
- Promotes **decoupling** of business logic from delivery (controller/UI)
- Facilitates **unit testing** of handlers
- Natural fit for **CQRS** (Command Query Responsibility Segregation)

### CQRS + MediatR + Clean Architecture (Typical Pattern)

```plaintext
[ API Controller ]
        ↓
[ IMediator.Send() ]
        ↓
[ Command / Query Handler ]
        ↓
[ Application Services / Repositories ]
```

### Summary

| Aspect | MediatR |
| --- | --- |
| Pattern | Mediator |
| Used for | Decoupling request handling |
| Works well with | Clean Architecture & CQRS |
| Pros | Decouples logic, testable, modular |
| Common Use | Handle Commands & Queries |


---

Original Source: https://www.mindstick.com/interview/34249/what-is-mediatr-and-how-does-it-relate-to-clean-architecture

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
