DEV Community

Cover image for Setting Up MediatR in a Minimal API
Spyros Ponaris
Spyros Ponaris

Posted on • Edited on

Setting Up MediatR in a Minimal API

Introduction

MediatR simplifies CQRS (Command Query Responsibility Segregation) by decoupling request handling logic in a Minimal API. This tutorial will guide you through setting up MediatR in an ASP.NET Core Minimal API.

Source Code

You can find the complete source code for this tutorial at:
👉 GitHub Repository

Benefits of CQRS Pattern

  • Using CQRS (Command Query Responsibility Segregation) provides several advantages:
  • Separation of Concerns - Queries (read operations) and Commands (write operations) are handled separately, making the codebase more maintainable.
  • Improved Performance - Read and write operations can be optimized independently, potentially using different storage mechanisms.
  • Scalability - Enables better horizontal scaling by distributing reads and writes across different services.
  • Better Security - Can implement stricter authorization rules for commands while keeping queries more open.
  • Simplifies Complex Business Logic - Helps structure applications with clearer boundaries for processing business rules.
  • Easier Testing - Since commands and queries are separate, unit tests can be written more effectively.

Want to learn more about Minimal API Performance Benchmark? Read my post: Minimal API Performance Benchmark .

A working Minimal API setup :

Step 1: Install Required Packages

Run the following commands to install MediatR and Entity Framework Core (InMemory for simplicity):

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

Enter fullscreen mode Exit fullscreen mode

Step 2: Configure MediatR in Program.cs

Modify your Program.cs file to include MediatR configuration:

builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblies(typeof(Program).Assembly));

// Register In-Memory Database
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseInMemoryDatabase("ContactsDb"));
Enter fullscreen mode Exit fullscreen mode

Define API endpoints with MediatR

app.MapGet("/contacts", async (IMediator mediator) => await mediator.Send(new GetContactsQuery()));

app.MapPost("/contacts", async (IMediator mediator, CreateContactCommand command) => await mediator.Send(command));
Enter fullscreen mode Exit fullscreen mode

Handler

public class GetContactsHandler(AppDbContext context) : IRequestHandler<GetContactsQuery, List<ContactItem>>
{
    private readonly AppDbContext _context = context;

    public async Task<List<ContactItem>> Handle(GetContactsQuery request, CancellationToken cancellationToken)
        => await _context.Contacts.ToListAsync(cancellationToken);
}

Enter fullscreen mode Exit fullscreen mode

Step 3: Run Your Application
Execute the following command to start your API:

dotnet run
Enter fullscreen mode Exit fullscreen mode

Step 4: Test API Endpoints

You can use Postman or cURL to test the API:

Create Contact: POST https://localhost:5001/contacts with JSON body:

{
  "name": "Test Contact",
  "email": "test@example.com"
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

You have successfully set up MediatR in a Minimal API! 🚀

Prerequisites

Ensure you have:

.NET 8 or later installed

References

Top comments (0)