Action Injection in WebAPI

Action injection in ASP.NET Core WebAPI refers to the process of injecting services directly into action methods of a controller. It allows you to obtain the required services for a specific action method without having to inject them into the controller's constructor.

In traditional dependency injection (DI), services are typically injected into a controller's constructor and are available for use throughout all action methods within that controller. However, there might be cases where you only need a service within a particular action method. In such scenarios, action injection can be used to inject the required service directly into the method's parameter.

‘[FromServices]’ is an attribute used in ASP.NET Core to inject services directly into action methods of your controllers.

The [FromServices] attribute for action injection has been available since the initial release of ASP.NET Core, which is ASP.NET Core 1.0. It has been a part of the framework since its inception and is used to inject services directly into action methods within controllers.

Here is a way to employ the [FromServices] attribute within an ASP.NET Core WebAPI controller:

The tools which I have leveraged for this tutorial.

  1. VS 2022 Community Edition
  2. .NET 6.0
  3. Web API

The source code can be downloaded from GitHub.

Define a service interface and its implementation:

public interface IMyService
{
    string GetServiceInfo();
}

public class MyService : IMyService
{
    public string GetServiceInfo()
    {
        return "Example on Action Injection";
    }
}

Configure the service in your Program.cs:

builder.Services.AddTransient<IMyService, MyService>();

Use [FromServices] attribute in your controller action method:

namespace ActionInjection.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MyController : ControllerBase
    {
        [HttpGet("info")]
        public IActionResult GetInfo([FromServices] IMyService myService)
        {
            var info = myService.GetServiceInfo();
            return Ok(info);
        }
    }
}

In this example, the GetServiceInfo action method uses [FromServices] attribute to directly inject the IMyService instance into the method parameter. ASP.NET Core will automatically resolve the service and provide it to the action method.

It's important to recognize that while leveraging [FromServices] can be advantageous under specific circumstances, the preferred approach for enhanced maintainability and testability—especially when a service is required across multiple action methods—is to opt for constructor injection (the constructor of the [Controller]).