Using MediatR with API Endpoints

Download full source code.

When working with minimal API endpoints, I try to keep business logic out of the endpoint itself.

The mediator pattern helps with this by putting the business logic inside handlers. [ This post will show how to use the MediatR library with a single API endpoint, but you can of course use it with multiple endpoints.

You need to add the MediatR.Extensions.Microsoft.DependencyInjection NuGet package to your project.

Here is my simple Program.cs file.

 1using MediatR;
 2using MediatrAPIEndpoints;
 3
 4var builder = WebApplication.CreateBuilder(args);
 5builder.Services.AddMediatR(typeof(Program));
 6var app = builder.Build();
 7
 8app.MapGet("/", async (int num1, int num2, IMediator mediator) =>
 9{
10    string result = await mediator.Send(new AddTwoNumbersRequest() { Num1 = num1, Num2 = num2 }, default);
11    return result;
12});
13
14app.Run();

On line 4, I register MediatR with the DI container.

On line 10, I send my request to my mediator. My mediator will then find the correct handler for the request and execute it.

Here is my request and request handler, not much to them.

 1using MediatR;
 2namespace MediatrAPIEndpoints;
 3
 4// MediatR Request
 5public class AddTwoNumbersRequest : IRequest<string>
 6{
 7    public int Num1 { get; init; }
 8    public int Num2 { get; init; }
 9}
10
11// MediatR Request Handler
12public class AddTwoNumbersRequestHandler : IRequestHandler<AddTwoNumbersRequest, string>
13{
14    public async Task<string> Handle(AddTwoNumbersRequest request, CancellationToken cancellationToken)
15    {
16        return $"You added {request.Num1} and {request.Num2}, the result is {request.Num1 + request.Num2}";
17    }
18}

To test it out, run the project and go to http://localhost:5000/?num1=1&num2=2. You will see the result.

There you go, MediatR with API endpoints. A nice way to keep your business logic out of your API endpoints.

Download full source code.

comments powered by Disqus

Related