How does ASP.NET Core's DI container support injecting a logger via ILogger<T>, and how is the generic type parameter used?
Short answer
ILogger is automatically resolvable for any type T without explicit registration, since the logging infrastructure registers a generic ILogger<> open generic factory -- the T parameter becomes the logger's 'category name' (typically the full type name), letting log output and…
Advertisement
AModel answer
ILogger<T> is automatically resolvable for any type T without explicit registration, since the logging infrastructure registers a generic ILogger<> open generic factory -- the T parameter becomes the logger's 'category name' (typically the full type name), letting log output and filtering be scoped precisely to the class that generated each log entry.
public class OrderService {
private readonly ILogger<OrderService> _logger;
public OrderService(ILogger<OrderService> logger) => _logger = logger;
public void Process() {
_logger.LogInformation("Processing order"); // logged with category 'OrderService'
}
}Real-world example
A production log filter configured to show only Warning+ level messages from OrderService (but Debug level from PaymentService) relies entirely on each class injecting its own correctly-typed ILogger<T>, which automatically tags every log entry with the right category.
Likely follow-ups
- How does the logging configuration system use these category names for filtering?
- Why is ILogger<T> registered without explicit AddScoped/AddSingleton calls?
Related topics