How to use the FromServices attribute in ASP.NET Core

By FoxLearn 2/26/2025 4:28:43 AM   19
ASP.NET Core has built-in support for dependency injection, allowing components to be injected at runtime. This makes your code more flexible, testable, and maintainable. Dependency injection can be performed in three ways: constructor injection, setter injection, and interface injection.

Constructor injection is the most commonly used method in ASP.NET Core. However, there are scenarios where it may not be the most suitable, especially if the dependency is only needed in a few action methods. In such cases, the FromServices attribute is a great solution. This attribute allows you to inject dependencies directly into controller action methods, making your code more efficient and cleaner.

Injecting a Logging Service with the FromServices Attribute

Consider the following example where we have a ILoggingService interface and its implementation LoggingService. The LoggingService is responsible for logging messages in the application.

public interface ILoggingService
{
    void Log(string message);
}

public class LoggingService : ILoggingService
{
    public void Log(string message)
    {
        // Log the message (e.g., write it to a file or database)
        Console.WriteLine($"Log: {message}");
    }
}

Register the Service in the ConfigureServices Method:

In the Startup.cs file, you need to register the LoggingService in the dependency injection container:

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

Inject the Dependency Using the FromServices Attribute:

Now, let’s create a controller that uses the ILoggingService to log messages. Instead of injecting the service through the constructor, we’ll use the FromServices attribute to inject the dependency directly into the action method.

using Microsoft.AspNetCore.Mvc;

namespace MyApplication.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LogController : ControllerBase
    {
        [HttpGet]
        public ActionResult<string> Get([FromServices] ILoggingService loggingService)
        {
            // Use the logging service to log a message
            loggingService.Log("Request received at Get endpoint.");

            return "Message logged successfully.";
        }
    }
}

In this example, the ILoggingService is injected into the Get action method via the FromServices attribute. This is particularly useful when you don't need the logging service across multiple actions in the controller, thus keeping the dependency injection clean and scoped to only where it’s needed.

Why Use the FromServices Attribute?

The FromServices attribute is particularly beneficial when a service is only required in specific action methods. This allows for a more fine-grained control of when and where the dependencies are injected. It can also reduce the overhead of maintaining unnecessary service instances for actions that do not require them.

Using the FromServices attribute in ASP.NET Core allows you to inject dependencies into controller action methods efficiently, without needing to maintain a service instance throughout the entire controller. This results in cleaner and more maintainable code, especially when the dependency is only used in one or a few action methods.