How to use the FromServices attribute in ASP.NET Core

Take advantage of the FromServices attribute in ASP.NET Core to inject dependencies directly into your action methods.

How to use the FromServices attribute in ASP.NET Core
Getty Images

ASP.NET Core has built-in support for dependency injection. You can use dependency injection in ASP.NET Core to plug in components at runtime, making your code more flexible and easier to test and maintain. There are three basic ways to inject dependencies, namely constructor injection, setter injection, and interface injection.

Constructor injection may be the most widely used way to inject dependencies in ASP.NET Core. However, constructor injection is not always an ideal choice, especially when you need dependencies in just one or a handful of methods. In such cases, it’s more efficient to take advantage of the FromServices attribute, which allows you to inject dependencies directly into the action methods of your controller.

This article presents a discussion of how we can use the FromServices attribute in ASP.NET Core to inject dependencies. We will also illustrate the most common way to inject dependencies in ASP.NET Core, constructor injection. 

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here

Create an ASP.NET Core API project in Visual Studio

First off, let’s create an ASP.NET Core project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.NET Core project in Visual Studio 2019.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed.
  4. Click Next
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Create. 
  7. In the “Create New ASP.NET Core Web Application” window, select .NET Core as the runtime and ASP.NET Core 2.2 (or later) from the drop-down list at the top. I’ll be using ASP.NET Core 3.0 here.
  8. Select “API” as the project template to create a new ASP.NET Core API application. 
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  10. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either.
  11. Click Create.

This will create a new ASP.NET Core API project in Visual Studio 2019. We’ll use this project to work with the FromServices attribute in the subsequent sections of this article.

Create a new controller in ASP.NET Core

Let’s create a new controller and use the FromServices attribute there. Follow the steps outlined below to create a new controller.

  1. Select the Controllers solution folder in the Solution Explorer window.
  2. Click “Add -> Controller…” to create a new controller.
  3. Select the template “API Controller with read/write actions.”
  4. Click Add.
  5. Name the controller SecurityController.
  6. Click Add to complete the process.

Use constructor injection in ASP.NET Core

Let us first examine how we can inject dependencies using constructor injection. Consider the following interface called ISecurityService.

public interface ISecurityService
{
    bool Validate(string userID, string password);
}
public class SecurityService : ISecurityService
{
    public bool Validate(string userID, string password)
    {
        //Write code here to validate the user credentials
        return true;
    }
}

To add the service to the container, you can write the following code in the ConfigureServices method of the Startup class.

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<ISecurityService, SecurityService>();
    services.AddControllers();
}

The following code snippet illustrates how you can use constructor injection in your controller.

 [Route("api/[controller]")]
 [ApiController]
  public class SecurityController : ControllerBase
    {
        private readonly ISecurityService _securityService;
        public SecurityController(ISecurityService securityService)
        {
            _securityService = securityService;
        }
        [HttpGet]
        public bool Get(string userId, string password)
        {
            return _securityService.Validate(userId, password);
        }
        //Other methods
    }

FromServicesAttribute class in ASP.NET Core

The FromServicesAttribute class pertaining to the Microsoft.AspNetCore.Mvc namespace can be used to inject a service directly into an action method. Here’s how the FromServicesAttribute class is defined in the Microsoft.AspNetCore.Mvc namespace.

public ref class FromServicesAttribute : Attribute, Microsoft::AspNetCore::Mvc::ModelBinding::IBindingSourceMetadata

The FromServices attribute, when used in your controller, specifies that a parameter in an action method should be bound to a service from the services container. In other words, when you use this attribute in an action method, the services container is used to resolve dependencies at runtime.

Use the FromServices attribute for dependency injection in ASP.NET Core

So far so good. Now, what if we don’t need the security service instance in other action methods? What’s the point in having an instance in memory that won’t get much reuse? This is exactly where the FromServices attribute comes to the rescue.

The following code snippet shows how you can take advantage of the FromServices attribute to inject dependency in your controller’s action method.

using Microsoft.AspNetCore.Mvc;
namespace IDGFromServicesDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SecurityController : ControllerBase
    {
        [HttpGet]
        public ActionResult<bool> Get([FromServices] ISecurityService
        securityService, string userId, string password)
        {
            return securityService.Validate(userId, password);
        }
        //Other methods
    }
}

Using the FromServices attribute in the method signature to inject dependencies is an ideal choice when those dependencies will be used in only a few action methods. You can take advantage of the FromServices attribute in your controller’s action methods to make your code clean, lean, and maintainable.

Copyright © 2019 IDG Communications, Inc.