Martijn
Martijn

Reputation: 12102

Why is Logger<MyClass> not automatically available as DI service

When trying to instantiate

public class MyClass : BackgroundService {
  private ILogger<MyClass> Logger {get;}
  public MyClass(Logger<MyClass> logger) {
    Logger = logger
  }
}

through .Net DI by registering MyClass through

services.AddHostedService<MyClass>();

When the class is activated, an exception is thrown:

System.InvalidOperationException: 'Unable to resolve service for type 'Microsoft.Extensions.Logging.Logger1[MyClass]' while attempting to activate 'MyClass'.'`

I understood that ILogger<T> should be automatically available for all types T.

What should I do to fix this?

Upvotes: 1

Views: 244

Answers (1)

Martijn
Martijn

Reputation: 12102

While ILogger<T> is automatically available, Logger<T> isn't.

Change the constructor parameter from Logger<MyClass> to ILogger<MyClass> and then everything should work.

Upvotes: 1

Related Questions