Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding C# FromServices

So iv just been thrown into some new code at work and its in C#. Now I'm not very familiar with C# and there are some things I really don't understand and the main one is Injecting into methods.

Now there is a WebAPI and it has controller that uses a class named "LocalFileStorage" which is a dependency from another project, the constructor for that class looks like this.

 public class LocalFileStorageHandler : IStorageHandler
    {
       *Bunch of private variables

        public LocalFileStorageHandler(DbContext dbContext, IConfiguration configuration, ILogger<LocalFileStorageHandler> logger)
        { code here}

Now in the controller class every method that uses the LocalFileStorage gets it injected as a parameter. Here is a example:

public async Task<IActionResult> ApiMapper([FromBody] dynamic request, [FromServices] IStorageHandler storageHandler)
        

Also in the project startup.cs we can find this line:

services.AddScoped<IStorageHandler, LocalFileStorageHandler>();

Now my understanding is that for each separate request made the Addscoped makes sure that the method gets its own instance of LocalFileStorage handler. I also understand that the "[FromServices]" attribute causes this instance to be injected into the method. However the one thing I don't understand and cant find anywhere in the code is where the LocalFileStorage objects get their "In parameters" for their constructor?

As by my understanding each injected instance of LocalFileStorage should also receive the parameters:

DbContext dbContext, IConfiguration configuration, ILogger<LocalFileStorageHandler> logger 

What am i missing here ?

Kind regards

like image 861
Mr.Gomer Avatar asked Jul 31 '26 00:07

Mr.Gomer


1 Answers

The DI container injects the dependencies for you. So somewhere, the DbContext, IConfiguration and ILogger has been registered/setup.

Then when you use the FromServices attribute, the DI container will try to resolve the type for you and inject all dependencies (if they are registered, if not, an exception will be thrown)

IConfiguration and ILogger are usually setup when building the host. DbContext are (usually) registered by using the AddDbContext extension method.

Link to configuration for ILogger: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-6.0#logging-providers

Link to configuration for IConfiguration: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0#default-configuration

Link to Dependency Injection fundamentals in ASP.Net Core : https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-6.0

like image 76
JOSEFtw Avatar answered Aug 03 '26 06:08

JOSEFtw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!