1

I created a sample ConsoleApp in Dotnet core 3.1 and added the Microsoft.Logging.Extension.Abstractions(5.0.0) package in it. I also used Microsoft.Extensions.DependencyInjection(6.0.0) and set up ServiceCollection as:

var container = new ServiceCollection();
container.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
container.AddSingleton<ILoggerFactory>(new MyFactory()); // test implementation
// Created ServiceProvider
var sp = container.BuildServiceProvider();

Then i resolved the logger as sp.GetService<ILogger<TestClass>>(); Once i resolved the logger it calls the LoggerFactory's CreateLogger method with CategoryName as the className with Namespace prefixed... My Question is how it is happening under the hood. It seems that GetService is calling the LoggerFactory's method. Any ideas about how LoggerFactory is instantiated and used by DI infrastructure?

NPras
  • 3,135
  • 15
  • 29
GPuri
  • 495
  • 4
  • 11
  • It gets regiestered on the first call to get the service and after that same instance is use. You should search how Singleton dependencies work. – Code Name Jack Dec 07 '21 at 19:28
  • I understand Singleton Dependencies what I am asking is how DI knows to use ILoggerFactory when ILogger is being resolved. – GPuri Dec 07 '21 at 19:31

1 Answers1

2

Logger<T> has a public constructor that depends on ILoggerFactory. That's how LoggerFactory is getting resolved.

public class Logger<T> : ILogger<T>
{
      public Logger(ILoggerFactory factory)
      {
           //.......
           //.......
        }
}

Here is the link to the source code.

https://github.com/aspnet/Logging/blob/master/src/Microsoft.Extensions.Logging.Abstractions/LoggerOfT.cs

Code Name Jack
  • 2,856
  • 24
  • 40