C
C#12mo ago
palapapa

✅ What is the purpose of `[FromServices]`

Aren't dependencies already being injected from the services registered?
4 Replies
cap5lut
cap5lut12mo ago
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)
mindhardt
mindhardt12mo ago
You need some place to inject into. Usually you do it via private readonly fields in your class that are set in constructor
public class CacheService
{
private readonly IMemoryCache _memoryCache;

public CacheService(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
}
public class CacheService
{
private readonly IMemoryCache _memoryCache;

public CacheService(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
}
But with controllers you can inject services directly in your methods via [FromServices]
Unknown User
Unknown User12mo ago
Message Not Public
Sign In & Join Server To View
Thinker
Thinker12mo ago
(or in minimal API endpoints catcorn