Home > Software engineering >  Understanding C# FromServices
Understanding C# FromServices

Time:11-12

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

CodePudding user response:

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://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-6.0#logging-providers

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

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

  • Related