ASP.NET Core MVC Interview Question #129
What is the difference between constructor injection and action injection?
Dependency Injection, Services, Error Handling, Logging & Performance Senior Advanced
Quick Interview Answer
Constructor injection supplies dependencies when the controller is created and is appropriate for services used by several actions. Action injection supplies a service only to a particular action, commonly through FromServices or service-binding support.
Detailed Explanation
Constructor injection supplies dependencies when the controller is created and is appropriate for services used by several actions. Action injection supplies a service only to a particular action, commonly through FromServices or service-binding support.
Constructor injection is usually clearer for core controller dependencies. Action injection can be useful for a dependency needed by only one action, but excessive use can make dependencies less visible at the controller level.
Code Example
public IActionResult Report(
[FromServices] IReportGenerator generator)
{
var report = generator.Generate();
return View(report);
}