本文介绍了为什么ASP.NET Core DI知道如何解析ILogger< T>而不是ILogger?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果类T包含对ILogger的依赖关系,则解决依赖关系:

If class T contains dependency on ILogger, dependency is resolved:

public class Foo
{
    private ILogger _logger;

    public Foo(ILogger<Foo> logger)
    {
        _logger = logger;
    }
}

,但以下操作无效,因为logger为空:

but the following does not work, as logger will be null:

public class Foo
{
    private ILogger _logger;

    public Foo(ILogger logger)
    {
        _logger = logger;
    }
}

推荐答案

日志记录将以下服务添加到DI

Logging adds the following services to DI

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

Logger<>取决于DI中的ILoggerFactory.

对于第二种情况,您需要注入ILoggerFactory而不是ILogger.

For your second scenario you would need to inject ILoggerFactory instead of ILogger.

public Foo(ILoggerFactory loggerFactory)
{
    _logger = loggerFactory.CreateLogger("logger name here");
}

这篇关于为什么ASP.NET Core DI知道如何解析ILogger&lt; T&gt;而不是ILogger?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:59