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; } }
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 .
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.
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.
Net Core ILogger Value cannot be null.
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"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With