How do C# 12 primary constructors interact with dependency injection in ASP.NET Core minimal APIs and controller classes?
Short answer
Primary constructors let a controller (or any DI-managed class) declare its injected dependencies directly in the class header, with those parameters usable throughout the entire class body — eliminating the separate private readonly field declarations and explicit constructor…
Advertisement
AModel answer
Primary constructors let a controller (or any DI-managed class) declare its injected dependencies directly in the class header, with those parameters usable throughout the entire class body — eliminating the separate private readonly field declarations and explicit constructor assignment boilerplate previously required for every injected dependency.
// Modern: primary constructor eliminates DI boilerplate
public class OrdersController(IOrderService orderService, ILogger<OrdersController> logger) : ControllerBase {
[HttpGet]
public IActionResult Get() {
logger.LogInformation("Fetching orders");
return Ok(orderService.GetAll());
}
}
// No separate private fields or explicit constructor body neededReal-world example
Reducing significant boilerplate in ASP.NET Core controllers and services that inject multiple dependencies via the constructor.
Likely follow-ups
- What's a real trade-off or gotcha of using primary constructor parameters directly, instead of assigning them to explicit readonly fields?
Related topics