ASP.NET Core Interview Question #61

What is method or action injection in ASP.NET Core?

Dependency Injection & Services Junior Beginner

Quick Interview Answer

Method injection supplies a dependency directly to a method rather than storing it on the class. In MVC controllers, an action parameter can request a registered service with the FromServices attribute.

Detailed Explanation

Method injection supplies a dependency directly to a method rather than storing it on the class. In MVC controllers, an action parameter can request a registered service with the FromServices attribute.

This can be useful when a dependency is needed by only one action and should not become a dependency of the entire controller.

For dependencies used by several actions, constructor injection is usually clearer. Minimal API handlers can also receive registered services directly as handler parameters.

Code Example

[HttpGet]
public IActionResult Status(
    [FromServices] IHealthReportService healthService)
{
    return Ok(healthService.GetStatus());
}

// Minimal API
app.MapGet("/time", (ISystemClock clock) => clock.UtcNow);