MediatR implements the mediator pattern in .NET, decoupling request handling from the caller. It’s become my go-to for organizing application logic.
Setup
dotnet add package MediatR
dotnet add package MediatR.Extensions.Microsoft.DependencyInjectionservices.AddMediatR(typeof(Startup));Request and Handler
public class GetUserQuery : IRequest<UserDto>
{
public int UserId { get; set; }
}
public class GetUserHandler : IRequestHandler<GetUserQuery, UserDto>
{
private readonly IUserRepository _repo;
public GetUserHandler(IUserRepository repo) => _repo = repo;
public async Task<UserDto> Handle(GetUserQuery request, CancellationToken ct)
{
var user = await _repo.GetByIdAsync(request.UserId);
return new UserDto { Id = user.Id, Name = user.Name };
}
}Using in Controller
[HttpGet("{id}")]
public async Task<ActionResult<UserDto>> Get(int id)
{
var user = await _mediator.Send(new GetUserQuery { UserId = id });
return Ok(user);
}Benefits
- Decoupled handlers – easy to test
- Pipeline behaviors for cross-cutting concerns
- Clean controller actions
References
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.