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 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos