1

我在 Dotnet core 3.1 中创建了一个示例 ConsoleApp,并在其中添加了 Microsoft.Logging.Extension.Abstractions(5.0.0) 包。我还使用了 Microsoft.Extensions.DependencyInjection(6.0.0) 并将 ServiceCollection 设置为:

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

然后我将记录器解析为sp.GetService<ILogger<TestClass>>();一旦我解决了记录器,它就会调用LoggerFactory 的 CreateLogger方法,其中 CategoryName 作为 className 并带有命名空间前缀......我的问题是它是如何在引擎盖下发生的。似乎 GetService 正在调用 LoggerFactory 的方法。关于 DI 基础设施如何实例化和使用 LoggerFactory 的任何想法?

4

1 回答 1

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

于 2021-12-07T19:48:23.653 回答