I see various libraries resolving ILogger<T>
from DI. For example, see Identity's SignInManager
class.
Where is ILogger<T>
registered with the DI container to make this possible?
All I have been able to find is a ILoggerFactory
instance being registered in Hosting's WebHostBuilder
class. This makes sense to allow resolving ILoggerFactory
, but not ILogger<T>
from application code.
From the Logging examples, in order to create an ILogger
, you have have to explicitly call factory.CreateLogger()
.
ILogger<> is registered here as Logger<>: https://github.com/aspnet/Logging/blob/master/src/Microsoft.Extensions.Logging/LoggingServiceCollectionExtensions.cs
Logger<> takes ILoggerFactory into its own constructor so it can create the actual logger of whatever type: https://github.com/aspnet/Logging/blob/master/src/Microsoft.Extensions.Logging.Abstractions/LoggerOfT.cs
So it seems like it is more simple to take a constructor dependency on a ILogger than to take one on ILoggerFactory in order to create a logger manually. But there are scenarios where you may need an ILoggerFactory if you need to create multiple types of loggers or new up other objects that also need to create loggers.
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