Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to resolve ILogger from Microsoft.Extensions.Logging

I've configured my console application's Main like so

var services = new ServiceCollection()     .AddLogging(logging => logging.AddConsole())     .BuildServiceProvider(); 

And then I try to use it in another class like so

private readonly ILogger _logger;      public MyClass(ILogger logger) {     _logger = logger; }  public void MyFunc() {     _logger.Log(LogLevel.Error, "My Message"); } 

System.InvalidOperationException: 'Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger'

I've tried the solutions here but it didn't work for me.

Edit Based on Yaakov's comment below and this Github comment I'm able to resolve it correctly by doing this

public MyClass(ILogger<MyClass> logger) {     _logger = logger; } 

I would have preferred to have this in the initial BuildServiceProvider but looks like I'm gonna have to repeat this every time I want to use the logger (or create my own ILogger).

like image 619
reggaemahn Avatar asked Oct 22 '18 03:10

reggaemahn


People also ask

How do I dispose of an ILogger?

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.

What is Microsoft extensions logging debug?

Extensions. Logging. This logger logs messages to a debugger monitor by writing messages with System. Diagnostics. Debug.

What is the difference between the ILogger and ILogger T interfaces?

ILogger<T> is derived from ILogger and adds no new functionality. If you're using dependency injection, an instance of ILogger<T> is usually injected into your type T . So, each time you have a constructor that takes an ILogger<T> , you are defining a “component” for your application.


1 Answers

ILogger is no longer registered by default but ILogger<T> is. If you still want to use ILogger you can register it manually with the following (in Startup.cs):

public void ConfigureServices(IServiceCollection services) {     var serviceProvider = services.BuildServiceProvider();     var logger = serviceProvider.GetService<ILogger<AnyClass>>();     services.AddSingleton(typeof(ILogger), logger);     ... } 

Where AnyClass can be something generic, such as:

public class ApplicationLogs { } 

So:

public void ConfigureServices(IServiceCollection services) {     var serviceProvider = services.BuildServiceProvider();     var logger = serviceProvider.GetService<ILogger<ApplicationLog>>();     services.AddSingleton(typeof(ILogger), logger);     ... } 

ILogger will now resolve via constructor injection.

like image 68
Sam Shiles Avatar answered Sep 17 '22 19:09

Sam Shiles