容器如何实际解析ILogger< T> [英] How container actually resolve ILogger<T>

查看:66
本文介绍了容器如何实际解析ILogger< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET Core 2中,当我们谈论日志记录时,只需通过 ILoggerFactory.AddProvider()注册提供程序或使用适当的扩展方法就足够了.然后,您将能够解析 ILogger< T> (无需注册已关闭的 ILogger<> ).我在 ILoggerFactory.CreateLogger< T> 调用与实际的 ILogger< T> 解析之间架起了一座桥梁:好像发生了魔术,但是我没有找到.有任何想法吗?

In ASP.NET Core 2, when we talking about logging, it is enough to just register providers via ILoggerFactory.AddProvider() or to use appropriate extension methods. Then you would be able to resolve ILogger<T> (without registration of closed ILogger<>'s). I'm struggling with a bridge between ILoggerFactory.CreateLogger<T> invocation and actual ILogger<T> resolution: seems like somewhere magic happens, but I didn't find where. Any ideas?

推荐答案

所有操作均始于

It all starts in ConfigureLogging:

public static IWebHostBuilder ConfigureLogging(
    this IWebHostBuilder hostBuilder,
    Action<ILoggingBuilder> configureLogging)
{
    return hostBuilder.ConfigureServices(
        collection => collection.AddLogging(configureLogging));
}

这里的重要电话是

The call of importance here is to AddLogging. I won't include the entire function here, but the registration process looks like this:

services.TryAdd(ServiceDescriptor.Singleton<ILoggerFactory, LoggerFactory>());
services.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>)));

从上面可以看到, ASP.NET核心依赖关系注入容器允许注册开放的仿制药.

最后, Logger< T> 的>构造器看起来像这样:

Finally, the constructor for Logger<T> looks like this:

public Logger(ILoggerFactory factory)
{
    // ...

    _logger = factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(typeof(T)));
}

其余的 Logger< T> 类只是对非通用 _logger 的传递,该类现在包括 T 的类型.

The rest of the Logger<T> class is just a passthrough to the non-generic _logger, which now includes the name of T's type.

这篇关于容器如何实际解析ILogger&lt; T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆