Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is ILogger<T> resolved via DI?

Tags:

asp.net-core

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().

like image 741
kspearrin Avatar asked Jul 31 '15 16:07

kspearrin


1 Answers

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.

like image 158
Joe Audette Avatar answered Sep 26 '22 17:09

Joe Audette