Take advantage of the FromServices attribute in ASP.NET Core to inject dependencies directly into your action methods. Credit: 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. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed. Click Next In the “Configure your new project” window shown next, specify the name and location for the new project. Click Create. 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. Select “API” as the project template to create a new ASP.NET Core API application. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either. 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. Select the Controllers solution folder in the Solution Explorer window. Click “Add -> Controller…” to create a new controller. Select the template “API Controller with read/write actions.” Click Add. Name the controller SecurityController. 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. Related content feature What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos