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?
AdvancedAnswer
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.