Back to results for “Namespaces”
C# › Modern C# Features (Global Usings, File-Scoped Namespaces, Top-Level Statements)

How do C# 12 primary constructors interact with dependency injection in ASP.NET Core minimal APIs and controller classes?

Advanced

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 needed
Real-world example Reducing significant boilerplate in ASP.NET Core controllers and services that inject multiple dependencies via the constructor.

Common follow-ups: What's a real trade-off or gotcha of using primary constructor parameters directly, instead of assigning them to explicit readonly fields?