Injecting an abstraction in the controller – Dependency Injection
In this last controller, we leverage the SOLID principles, constructor injection, and, inherently, the Strategy pattern to build a controller that we can change from the outside. All we have to do to make the code flexible is inject the interface instead of its implementation, like this: using Microsoft.AspNetCore.Mvc;using Strategy.Services;namespace Strategy.Controllers;[Route(“travel/[controller]”)][ApiController]public class InjectAbstractionLocationsController : ControllerBase{ […]
Control Freak controllers – Dependency Injection
This first version of the code showcases the lack of flexibility that creating dependencies using the new keyword brings when the time to update the application arises. Here’s the initial controller that leverages an in-memory collection: using Microsoft.AspNetCore.Mvc;using Strategy.Services;namespace Strategy.Controllers;[Route(“travel/[controller]”)][ApiController]public class ControlFreakLocationsController : ControllerBase{ [HttpGet] public async Task<IEnumerable<LocationSummary>> GetAsync(CancellationToken cancellationToken) { var locationService = new […]