How to resolve dependencies in ASP.NET Core

Dependency injection is a technique that permits you to inject the dependent objects of a distinct class rather than build those people cases instantly. Employing dependency injection enhances testability and upkeep by facilitating free coupling. Furthermore, dependency injection permits you to modify your implementations without acquiring to modify the dependent forms that count on them.

Dependency injection is a very first-class citizen in ASP.Internet Main. The created-in dependency injection supplier in ASP.Internet Main is not as characteristic-abundant as IoC (inversion of control) containers this sort of as StructureMap and Ninject, but it is rapidly, effortless to configure, and effortless to use. You can inject both equally framework solutions and software solutions in ASP.Internet Main.

This write-up talks about the many methods in which you can solve dependencies in ASP.Internet Main.

To perform with the code illustrations delivered in this write-up, you need to have Visible Studio 2022 set up in your program. If you do not by now have a copy, you can obtain Visible Studio 2022 listed here.

Generate an ASP.Internet Main venture in Visible Studio 2022

Very first off, let us build an ASP.Internet Main venture in Visible Studio 2022. Following these methods will build a new ASP.Internet Main World wide web API six venture in Visible Studio 2022:

  1. Start the Visible Studio 2022 IDE.
  2. Click on “Create new venture.”
  3. In the “Create new project” window, decide on “ASP.Internet Main World wide web API” from the list of templates shown.
  4. Click Upcoming.
  5. In the “Configure your new project” window, specify the identify and site for the new venture.
  6. Optionally check out the “Place alternative and venture in the same directory” check out box, relying on your choices.
  7. Click Upcoming.
  8. In the “Additional Information” window shown up coming, decide on .Internet six. as the goal framework from the drop-down list at the major. Depart the “Authentication Type” as “None” (default).
  9. Make sure that the check out bins “Enable Docker,” “Configure for HTTPS,” and “Enable Open API Support” are unchecked as we won’t be making use of any of those people capabilities listed here. You can optionally uncheck the “Use controllers (uncheck to use small APIs)” check out box as nicely due to the fact we’ll be producing our individual controller.
  10. Click Generate.

This will build a new ASP.Internet Main six World wide web API venture in Visible Studio 2022. We’ll use this venture to illustrate resolving dependencies in the subsequent sections of this write-up.

Resolve dependencies making use of constructor injection

Now build the pursuing interface:

    public interface ICustomFileLogger
        public string Textual content get set
        public void Log(string information)

For the sake of simplicity, this is a small representation. The CustomFileLogger class implements the ICustomFileLogger interface as shown in the code snippet supplied beneath.

public class CustomFileLogger : ICustomFileLogger

   public string Textual content get set
   public void Log(string information)
      //Publish your individual implementation listed here

You can register an instance of sort ICustomFileLogger as a scoped service in the ConfigureServices approach if you’re making use of ASP.Internet 5, or in the Program.cs file if you’re making use of ASP.Internet six.


Upcoming, build an API controller named DefaultController and enter the pursuing code:

    public class DefaultController : ControllerBase
        non-public ICustomFileLogger _logger
        public DefaultController(ICustomFileLogger logger)
            _logger = logger
            if(string.IsNullOrEmpty(_logger.Textual content))
                _logger.Textual content = DateTime.UtcNow.ToString()
        public string Get()
            return "Hello World!"

Note how constructor injection has been made use of listed here. The constructor of the DefaultController class accepts an instance of sort ICustomFileLogger as a parameter.

Resolve dependencies making use of motion approach injection

You need to use constructor injection anytime you will need to use the injected instance in various techniques. If you need to use the instance in a distinct motion approach only, it is far better to inject the instance in the motion approach rather than use constructor injection.

The pursuing code snippet illustrates how motion approach injection can be reached.

public IActionResult Log([FromServices] ICustomFileLogger customFileLogger)

   //Publish your code listed here
    return Ok()

You may possibly often need to inject many distinctive solutions in your controller. If you’re making use of constructor injection, you would then have to specify numerous parameters in the constructor. A far better alternative to this is to use IServiceProvider.

Resolve dependencies making use of IServiceProvider

You can use the IServiceCollection interface to create a dependency injection container. The moment the container has been established, the IServiceCollection instance is composed into an IServiceProvider instance. You can use this instance to solve solutions. 

You can inject an instance of type IServiceProvider into any approach of a class. You can also acquire edge of the ApplicationServices home of the IApplicationBuilder interface and the RequestServices home of the HttpContext class to retrieve an IServiceProvider instance.

The pursuing code snippet illustrates how you can inject an instance of sort IServiceProvider.

public class DefaultController : Controller

    non-public IServiceProvider _supplier
    public DefaultController(IServiceProvider supplier)
        _supplier = supplier

You can use the pursuing code snippet in your motion techniques to retrieve any of the service cases you need.

ICustomFileLogger logger = (ICustomFileLogger)_supplier.GetService(typeof(ICustomFileLogger))

Note how the GetService approach of IServiceProvider is made use of to retrieve the service instance.

You can use the RequestServices home of the HttpContext class to retrieve an instance of sort IServiceProvider and then use this instance to call the GetService approach. The pursuing code exhibits how this can be performed.

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

Dependency injection is an strategy that enhances code upkeep and testability by facilitating free coupling. You can use the created-in dependency injection help in ASP.Internet Main to build purposes that are modular, lean, and clear, as nicely as less complicated to keep and take a look at.

Copyright © 2021 IDG Communications, Inc.