How does dependency injection differ in practice between controllers (constructor injection) and minimal APIs (parameter injection)?
Short answer
Controllers exclusively use constructor injection, resolving all dependencies once when the controller instance is created per-request.
Advertisement
AModel answer
Controllers exclusively use constructor injection, resolving all dependencies once when the controller instance is created per-request. Minimal APIs support injecting services directly as handler delegate parameters (automatically inferred as [FromServices] for registered service types not matching route/body binding patterns), letting each individual endpoint declare exactly the specific dependencies it needs without a shared constructor across multiple actions, which can reduce unnecessary coupling when different endpoints in the same feature area need different subsets of dependencies.
// Controller: all actions share the same constructor-injected dependencies
public class ProductsController(IProductService service, ILogger<ProductsController> logger) : ControllerBase {
[HttpGet] public IActionResult GetAll() => Ok(service.GetAll()); // has logger even if unused here
}
// Minimal API: each endpoint declares only what it actually needs
app.MapGet("/products", (IProductService service) => service.GetAll()); // no unused logger dependency
app.MapPost("/products", (IProductService service, ILogger<Program> logger, ProductDto dto) => { ... });Real-world example
A minimal API's simple GET endpoint declares only IProductService as a dependency, while its more complex POST endpoint additionally declares ILogger, avoiding the controller pattern's tendency to inject dependencies into a shared constructor that not every action actually uses.
Likely follow-ups
- Does this parameter-based injection have any measurable performance difference from constructor injection?
- How does this affect testability compared to controller-based DI?
Related topics