Why ASP.NET Core DI knows how to resolve ILogger

2019-01-26 04:50发布

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

public class Foo
{
    private ILogger _logger;

    public Foo(ILogger<Foo> 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;
    }
}

2条回答
你好瞎i
2楼-- · 2019-01-26 05:05

Logging adds the following services to DI

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

and Logger<> depends on ILoggerFactory from DI.

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

public Foo(ILoggerFactory loggerFactory)
{
    _logger = loggerFactory.CreateLogger("logger name here");
}
查看更多
看我几分像从前
3楼-- · 2019-01-26 05:14

Your first scenerio works because ILogger<> inherits from ILogger(see source code)

public interface ILogger<out TCategoryName> : ILogger
{

}

But as @KiranChalla said, in the LoggingServiceCollectionExtensions ILogger<> is registered(not ILogger) so your second scenerio does not work.

查看更多
登录 后发表回答