As we start implementing an API in ASP.Net core we usually repeat the constructor on each controller and the decorators for each controller class, for example:
[ApiController]
[Route("api/[controller]")]
public class ToDoController : ControllerBase
{
private readonly IMediator _mediator;
//constructor for each controller
public ActivitiesController(IMediator mediator)
{
_mediator = mediator;
}
}
In the above example, we use some decorators to indicate that our class is a controller, and then we specify the route for our controller, after that, we add a constructor for each class that receive all the dependencies from the DI Container, in the example w receive an IMediator implementation that allows us to use our CQRS implementation with MediatR
Now it's time to refactor the code
For that we can made our controllers thinner adding an abstraction for the ControllerBase
class :
First, write a class that acts as a controller base, this class will be our controller base for each controller in our project
[ApiController]
[Route("api/[controller]")]
public class BaseApiController:ControllerBase
{
private IMediator _mediator;
protected IMediator Mediator => _mediator ??= HttpContext.RequestServices
.GetService<IMediator>();
}
Then refactor the controllers implementing the BaseApiController
:
public class ToDoController : BaseApiController
{
}
public class UserController : BaseApiController
{
}
public classBooksController : BaseApiController
{
}
And that's all! , now for each controller, we just use our BaseApiController