How LoggerFactory in Dotnet core gets called

792 views Asked by At

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?

1

There are 1 answers

0
Code Name Jack On

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