Inject ILogger<T> into constructor that only expects ILogger

Viewed 138

This is similar to How to inject named logger generic ILogger<T> as ILogger into constructor using IServiceCollection and NLog

However I am looking for a solution using Serilog + Autofac.

Hopefully there is a solution that works for both ASP.net Core 6 and console .NET 6

Typically MEL ILogger is used like this:


public class MyClass
{
  private readonly ILogger _logger;

  public MyClass(ILogger<MyClass> logger) 
  {
    _logger = logger;
    _logger.LogInformation("Constructor");
  }
}

It is tedious to manually type ILogger<MyClass> everywhere like ILogger<MyOtherClass>, ILogger<YetAnotherClass>

Is there a way to omit the <MyClass> part, but actually receive ILogger<MyClass> like below? (Apparently in How to inject named logger generic ILogger<T> as ILogger into constructor using IServiceCollection and NLog the questioner claims to have a solution using Autofac, but I do not have enough Reputation to ask him in the comment)

public class MyClass
{
  private readonly ILogger _logger;

//public MyClass(ILogger<MyClass> logger)
  public MyClass(ILogger logger) // <<<<< notice that ILogger is used, instead of ILogger<T>
  {
    _logger = logger;
    _logger.LogInformation("Constructor");
  }
}

Thank you in advance.

1 Answers
Related