✅ What is the purpose of `[FromServices]`
Aren't dependencies already being injected from the services registered?
4 Replies
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.(https://www.infoworld.com/article/3451821/how-to-use-the-fromservices-attribute-in-aspnet-core.html)
You need some place to inject into. Usually you do it via
private readonly
fields in your class that are set in constructor
But with controllers you can inject services directly in your methods via [FromServices]
Unknown User•16mo ago
Message Not Public
Sign In & Join Server To View
(or in minimal API endpoints