ASP.NET Core MVC Interview Question #126
How is dependency injection used in ASP.NET Core MVC controllers?
Dependency Injection, Services, Error Handling, Logging & Performance Senior Advanced
Quick Interview Answer
ASP.NET Core has a built-in dependency injection container. A controller normally declares its required services as constructor parameters, and the framework resolves those services when it creates the controller.
Detailed Explanation
ASP.NET Core has a built-in dependency injection container. A controller normally declares its required services as constructor parameters, and the framework resolves those services when it creates the controller.
Constructor injection makes dependencies explicit and improves testability. Controllers should depend on abstractions or application services rather than constructing database contexts, repositories, HTTP clients, or other infrastructure directly.
Code Example
public class ProductsController : Controller
{
private readonly IProductService _service;
public ProductsController(IProductService service)
{
_service = service;
}
public IActionResult Index() => View();
}