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?
You need
MyUtility<P>
, so inject that instead ofILogger<T>
.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 (likeIMyUtility<P>
) - then you could add it to the container with open generics:That way you could inject the interfaces instead:
Then it would be easier for you to test your controller (by mocking the interfaces).