Streamlining CQRS in .NET Minimal APIs with MediatR
MediatR is a powerful tool that simplifies implementing the Command Query Responsibility Segregation (CQRS) pattern in .NET Minimal APIs. This pattern decouples read (queries) and write (commands) operations, leading to a more maintainable and scalable application. This guide demonstrates how to integrate MediatR into your .NET Minimal API project.
Benefits of CQRS
CQRS offers several key advantages:
- Separation of Concerns: Decoupling read and write operations simplifies development and maintenance.
- Improved Performance: Optimize read and write operations independently, potentially leveraging different data access strategies.
- Enhanced Scalability: Distribute read and write workloads across multiple services for improved performance and resilience.
- Reinforced Security: Implement granular authorization policies for commands and queries.
- Simplified Complex Logic: CQRS provides a structured approach to managing complex business rules.
- Testability: Separate commands and queries are easier to unit test.
Setting Up MediatR in Your Minimal API
Prerequisites
- .NET 8 SDK (or later)
1. Install NuGet Packages
Install the necessary NuGet packages using the following commands:
dotnet add package MediatR
dotnet add package MediatR.Extensions.Microsoft.DependencyInjection
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.InMemory
2. Configure MediatR and Database Context
In your Program.cs
file, configure MediatR and register your database context (using InMemory database for this example):
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblies(typeof(Program).Assembly));
// Register In-Memory Database
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseInMemoryDatabase("ContactsDb"));
3. Define API Endpoints
Use MediatR to handle requests in your Minimal API endpoints:
app.MapGet("/contacts", async (IMediator mediator) => await mediator.Send(new GetContactsQuery()));
app.MapPost("/contacts", async (IMediator mediator, CreateContactCommand command) => await mediator.Send(command));
4. Run and Test
Start your application:
dotnet run
Test your API endpoints using a tool like Postman or curl. For example, to create a contact:
POST /contacts
{
"name": "Test Contact",
"email": "[email protected]"
}
Conclusion
By integrating MediatR, your Minimal API can leverage the benefits of CQRS, resulting in a more robust and maintainable application architecture. This approach simplifies development, improves performance, and enhances scalability.
Further Resources
- 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