C
C#2y ago
Hugh

❔ Creating a class that takes a Logger for both the class and its base class

I'm trying to figure out the best way to use Loggers in my app. All of the documentation that I've seen says to use Dependency Injection for this, and do something like:
public class MyClass
{
private readonly ILogger<MyClass> _logger;
public MyClass(ILogger<MyClass> logger)
{
_logger = logger;
}
}
public class MyClass
{
private readonly ILogger<MyClass> _logger;
public MyClass(ILogger<MyClass> logger)
{
_logger = logger;
}
}
However, what I can't figure out is how I would do this when I have a MyBaseClass and a MyClass which is a subclass of MyBaseClass. I can't pass the same object from one constructor to the other. Thanks
9 Replies
ero
ero2y ago
why can't you pass between ctors?
Hugh
HughOP2y ago
Because the type that will be created in MyClass will be an ILogger<MyClass>, and the one that MyBaseClass expects is an ILogger<MyBaseClass> oooh - I've just realised that it doesn't have to be the same as the class that it's being passed into... That will certainly sort me out here
ero
ero2y ago
ah, of course, covarience... or the other one, whichever
Hugh
HughOP2y ago
So I'll just get MyClass to expect an ILogger<MyBaseClass>
Anton
Anton2y ago
just take an ILogger in the base class
Hugh
HughOP2y ago
Ah, that's even better then if that will work
Anton
Anton2y ago
or a logger factory and then create one in the base constructor the generic parameter is just to give a name to the logs
Hugh
HughOP2y ago
If I can use an ILogger<MyClass> even when MyBaseClass is doing logging, then that's even better right Thanks both
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server