ASP Core add logging in utility classes

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).

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top