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
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"));
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));
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);
}
Step 3: Run Your Application
Execute the following command to start your API:
dotnet run
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"
}
Conclusion
You have successfully set up MediatR in a Minimal API! 🚀
Prerequisites
Ensure you have:
.NET 8 or later installed
References
- Entity Framework Core: https://learn.microsoft.com/en-us/ef/core/
- MediatR: https://github.com/jbogard/MediatR
- CQRS Pattern: https://learn.microsoft.com/en-us/azure/architecture/patterns/cqrs
Top comments (0)