Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ASP.NET Core DI knows how to resolve ILogger<T>, but not ILogger?

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;     } } 
like image 503
Set Avatar asked Jul 07 '16 20:07

Set


People also ask

What is the difference between ILogger and ILoggerFactory?

ILogger: is responsible to write a log message of a given Log Level. ILoggerFactory: you can register one or more ILoggerProvider s with the factory, which in turn uses all of them to create an instance of ILogger . ILoggerFactory holds a collection of ILoggerProviders .

What is the use of ILogger in .NET core?

ILoggerFactory is a factory interface that we can use to create instances of the ILogger type and register logging providers. It acts as a wrapper for all the logger providers registered to it and a logger it creates can write to all the logger providers at once.

How do I dispose of an ILogger?

In short, if you want to write a custom ILoggerFactory with an ILogger class that needs to be disposed, you will have to keep the ILogger objects in a private list in your ILoggerProvider and dispose them all when the Dispose is called.

Can ILogger be null?

Net Core ILogger Value cannot be null.


1 Answers

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"); } 
like image 164
Kiran Avatar answered Sep 18 '22 22:09

Kiran