0

This issue is different, I know what DI is, but I want to know how asp.net core use DI. We can configure custom logging in ASP.NET Core, but I do not know why it works.

Normally, we use the new keyword to instantiate a class, and then we can use it in the controller. In ASP.NET Core, we use a controller constructor with parameter like below:

public class HomeController : Controller
{
    private readonly ILogger _logger;
    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }
}

I know it is a design pattern called Dependency Injection, but I am wondering how this is implemented. How did the ASP.NET Core team realize this?

Edward
  • 28,296
  • 11
  • 76
  • 121
  • Your question is unclear. You might want to rephrase your question. You are "wondering depth implementation of this"? What? – Steven Feb 06 '17 at 10:22
  • @Steven I am wondering when ILogger is initialized in public HomeController(ILogger logger), or when the logger get value? – Edward Feb 06 '17 at 10:31
  • 1
    Possible duplicate of [What is dependency injection?](http://stackoverflow.com/questions/130794/what-is-dependency-injection) – NightOwl888 Feb 06 '17 at 11:01

1 Answers1

0

In Dependency Injection and Inversion of Control jargon, what is injected is called a "service".

You register your services with an IoC container upon application startup, meaning: you tie concrete implementations and a lifetime to a certain type.

Now when a controller is required to serve an incoming request, MVC will use a controller factory to look up and instantiate the relevant controller. When that controller has constructor parameters, it'll ask the IoC container to resolve the required service parameters.

More information on learn.microsoft.com: Dependency injection into controllers.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • could you share me key code related with "a controller factory to look up and instantiate the relevant controller. When that controller has constructor parameters, it'll ask the IoC container to resolve the required service parameters". I am wondering how IoC container to resolve the required service parameters – Edward Feb 06 '17 at 10:34
  • 2
    You can put each of those search terms in your favorite web search engine. Explaining in detail how to build an IoC container would be too broad and not fit into a single answer. A relevant keyword is "reflection", used to inspect types and methods at runtime. – CodeCaster Feb 06 '17 at 10:35