asp.net-core – Dependency Injection – Injecting a dependency into a Controller Action

A less known builtin feature is Controller Action injection using the FromServicesAttribute.

[HttpGet]
public async Task<IActionResult> GetAllAsync([FromServices]IProductService products)
{
     return Ok(await products.GetAllAsync());
}

An important note is that the [FromServices] can not be used as general "Property Injection" or "Method injection" mechanism! It can only be used on method parameters of an controller action or controller constructor (in the constructor it’s obsolete though, as ASP.NET Core DI system already uses constructor injection and there are no extra markers required).

It can not be used anywhere outside of a controllers, controller action. Also it is very specific to ASP.NET Core MVC and resides in the Microsoft.AspNetCore.Mvc.Core assembly.

Original quote from the ASP.NET Core MVC GitHub issue (Limit [FromServices] to apply only to parameters) regarding this attribute:

@rynowak:

@Eilon:

The problem with properties is that it appears to many people that it can be applied to any property of any object.

Agreed, we’ve had a number of issues posted by users with confusion around how this feature should be used. There’s really been a fairly large amount of feedback both of the kinds " [FromServices] is weird and I don’t like it" and " [FromServices] has confounded me". It feels like a trap, and something that the team would still be answering questions about years from now.

We feel like most valuable scenario for [FromServices] is on method parameter to an action for a service that you only need in that one place.

/cc @danroth27 – docs changes

To anyone in love with the current [FromServices] , I’d strongly recommend looking into a DI system that can do property injection (Autofac, for example).

Notes:

  • Any services registered with the .NET Core Dependency Injection system can be injected inside an controller’s action using the [FromServices] attribute.

  • Most relevant case is when you need a service only in a single action method and don’t want to clutter your controller’s constructor with another dependency, which will only be used once.

  • Can’t be used outside of ASP.NET Core MVC (i.e. pure .NET Framework or .NET Core console applications), because it resides in Microsoft.AspNetCore.Mvc.Core assembly.

  • For property or method injection you must use one of third-party IoC containers available (Autofac, Unity, etc.).

if you want to reproduce, please indicate the source:
asp.net-core – Dependency Injection – Injecting a dependency into a Controller Action - CodeDay