How to resolve dependencies in ASP.NET Core

Dependency injection is a technique that allows you to inject the hanging objects of a particular class rather than form those entreatys straightly. Using dependency injection enhances testability and livelihood by facilitating loose coupling. Additionally dependency injection allows you to modify your implementations without having to change the hanging types that rely on them.

Dependency injection is a first-class townsman in ASP.NET Core. The built-in dependency injection provider in ASP.NET Core is not as feature-rich as IoC (reversal of control) containers such as StructureMap and Ninject but it is fast easy to configure and easy to use. You can inject both framework labors and application labors in ASP.NET Core.

[ Also on InfoWorld: The best open rise software of 2021 ]

This article talks almost the different ways in which you can resolve dependencies in ASP.NET Core.

To work with the code examples granted in this article you should have Visual Studio 2022 installed in your order. If you dont already have a copy you can download Visual Studio 2022 here.

Create an ASP.NET Core project in Visual Studio 2022

First off lets form an ASP.NET Core project in Visual Studio 2022. Following these steps will form a new ASP.NET Core Web API 6 project in Visual Studio 2022:

  1. Launch the Visual Studio 2022 IDE.
  2. Click on ’Create new project.’
  3. In the ’Create new project’ window select ’ASP.NET Core Web API’ from the list of templates displayed.
  4. Click Next.
  5. In the ’Configure your new project’ window particularize the name and location for the new project.
  6. Optionally check the ’Place solution and project in the same directory’ check box depending on your preferences.
  7. Click Next.
  8. In the ’Additional Information’ window shown next select .NET 6.0 as the target framework from the drop-down list at the top. Leave the ’Authentication Type’ as ’None’ (lapse).
  9. Ensure that the check boxes ’Enable Docker’ ’Configure for HTTPS’ and ’Enable Open API Support’ are unchecked as we wont be using any of those features here. You can optionally uncheck the ’Use controllers (uncheck to use minimal APIs)’ check box as well owing well be creating our own controller.
  10. Click Create.

This will form a new ASP.NET Core 6 Web API project in Visual Studio 2022. Well use this project to elucidate resolving dependencies in the posterior sections of this article.

Resolve dependencies using constructor injection

Now form the following interface:

    open interface ICustomFileLogger
        open string Text { get; set; }
        open void Log(string communication);

For the sake of artlessness this is a minimal representation. The CustomFileLogger class implements the ICustomFileLogger interface as shown in the code snippet given under.

open class CustomFileLogger : ICustomFileLogger
   open string Text { get; set; }
   open void Log(string communication)
      //Write your own implementation here

You can register an entreaty of type ICustomFileLogger as a scoped labor in the ConfigureServices order if youre using ASP.NET 5 or in the Program.cs file if youre using ASP.NET 6.

labors.AddScopedlt;ICustomFileLogger CustomFileLoggergt;();

Next form an API controller named DefaultController and invade the following code:

    open class DefaultController : ControllerBase
        special ICustomFileLogger _logger;
        open DefaultController(ICustomFileLogger logger)
            _logger = logger;
                _logger.Text = DateTime.UtcNow.ToString();
        open string Get()
            recur "Hello World!";

Note how constructor injection has been used here. The constructor of the DefaultController class accepts an entreaty of type ICustomFileLogger as a parameter.

Resolve dependencies using action order injection

You should use constructor injection whenever you will need to use the injected entreaty in multiple orders. If you need to use the entreaty in a particular action order only it is better to inject the entreaty in the action order rather than use constructor injection.

The following code snippet elucidates how action order injection can be achieved.

open IActionResult Log([FromServices] ICustomFileLogger customFileLogger)
   //Write your code here
    recur Ok();

You might frequently need to inject many different labors in your controller. If youre using constructor injection you would then have to particularize separate parameters in the constructor. A better solution to this is to use IServiceProvider.

Resolve dependencies using IServiceProvider

You can use the IServiceCollection interface to form a dependency injection container. Once the container has been formd the IServiceCollection entreaty is composed into an IServiceProvider entreaty. You can use this entreaty to resolve labors. 

You can inject an entreaty of type IServiceProvider into any order of a class. You can also take gain of the ApplicationServices property of the IApplicationBuilder interface and the RequestServices property of the HttpContext class to recover an IServiceProvider entreaty.

The following code snippet elucidates how you can inject an entreaty of type IServiceProvider.

open class DefaultController : Controller
    special IServiceProvider _provider;
    open DefaultController(IServiceProvider provider)
        _provider = provider;

You can use the following code snippet in your action orders to recover any of the labor entreatys you need.

ICustomFileLogger logger = (ICustomFileLogger)_provider.GetService(typeof(ICustomFileLogger));

Note how the GetService order of IServiceProvider is used to recover the labor entreaty.

You can use the RequestServices property of the HttpContext class to recover an entreaty of type IServiceProvider and then use this entreaty to call the GetService order. The following code shows how this can be done.

ICustomFileLogger logger = (ICustomFileLogger)HttpContext.RequestServices.GetService(typeof(ICustomFileLogger));

Dependency injection is an access that enhances code livelihood and testability by facilitating loose coupling. You can use the built-in dependency injection support in ASP.NET Core to form applications that are modular lean and clean as well as easier to maintain and test.