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 .