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?
Logger<T>
has a public constructor that depends onILoggerFactory
. That's howLoggerFactory
is getting resolved.Here is the link to the source code.
https://github.com/aspnet/Logging/blob/master/src/Microsoft.Extensions.Logging.Abstractions/LoggerOfT.cs