Search code examples
asp.net-coreiloggeriloggerfactory

ASP Core add logging in utility classes


We automatically get the logger injected into the generic controller class. But how do we derive a logger for generic utility classes that have different generic types than the enclosing Controller?

public partial class GenericController<T> {
    public GenericController(ILogger<T> logger) 
    {  
          MyUtility<DifferentClass> utlDifferent = new MyUtility<DifferentClass>( /*????*/ );
          MyUtility<AnotherClass>   utlAnother   = new MyUtility<AnotherClass>( /*????*/ );
    }
}
...
public class MyUtility<P> {
    public MyUtility<P>(ILogger<P> logger) { }
}

Is there a way to get the LoggerFactory that created the injected logger instance and use it to generate a new logger with all of the same providers?


Solution

  • You need MyUtility<P>, so inject that instead of ILogger<T>.

    public GenericController(MyUtility<DifferentClass> utlDifferent, MyUtility<AnotherClass> utlAnother)
    {  
    }
    

    Avoid directly instantiating objects yourself (with new ...). Let the container handle that and just inject what you need directly.

    Note: this would be easier if MyUtility<P> implemented an interface (like IMyUtility<P>) - then you could add it to the container with open generics:

    services.AddScoped(typeof(IMyUtility<>), typeof(MyUtility<>));
    

    That way you could inject the interfaces instead:

    public GenericController(IMyUtility<DifferentClass> utlDifferent, IMyUtility<AnotherClass> utlAnother)
    {  
    }
    

    Then it would be easier for you to test your controller (by mocking the interfaces).