Table of contents
The Problem
A runtime error is triggered when using the Microsoft ILogger class in your .Net applications.
System.InvalidOperationException: ‘Unable to resolve service for type ‘Microsoft.Extensions.Logging.ILogger’
Common Steps to Reproduce
Configuration 1
Console application Main configuration
var services = new ServiceCollection()
.AddLogging(logging => logging.AddConsole())
.BuildServiceProvider();
Class implementation
private readonly ILogger _logger;
public MyService(ILogger logger)
{
_logger = logger;
}
public void Execute()
{
_logger.LogInformation("My Message");
}
The Solution
Configuration 1
ILogger is no longer registered by default but ILogger<T> is.
Incorrect implementation
private readonly ILogger _logger;
public MyService(ILogger logger)
{
_logger = logger;
}
public void Execute()
{
_logger.LogInformation("My Message");
}
Correct implementation
private readonly ILogger _logger;
public MyService(ILogger<MyService> logger)
{
_logger = logger;
}
public void Execute()
{
_logger.LogInformation("My Message");
}
Using Logger in Startup.cs or Main.cs
Create a generic class to use with ILogger
public class ApplicationLogger
{
}
Use ILogger with generic class in Startup or Main
public void ConfigureServices(IServiceCollection services)
{
var serviceProvider = services.BuildServiceProvider();
var logger = serviceProvider.GetService<ILogger<ApplicationLogger>>();
//Add Singleton if you want to use Generic class logger in place of ILogger<T>
services.AddSingleton(typeof(ILogger), logger);
}
