I have a base class that does some work, including logging. I have an ILogger dependency injected into the constructor
public abstract class BaseClassExample
{
protected readonly ILogger<BaseClassExample> logger;
public BaseClassExample(ILogger<BaseClassExample> logger)
{
this.logger = logger;
}
}
And I want to have classes implement BaseClassExample, and do their own work too, also including logging.
public class DerivedClass : BaseClassExample
{
protected readonly ILogger<DerivedClass> logger;
public DerivedClass(ILogger<DerivedClass> logger)
{
this.logger = logger;
}
}
Is this the right way of doing things? Am I supposed to get the implementing class's type for logging for the base class? Should I have a separate instance of a logger (with the DerivedClass's type) or try and use the same one as the base class?
Internally, an ILogger has a “name” (also called a “category”). The idea is that each ILogger instance is used by a different component of the application. ILogger is a base interface that provides the core logging functionality, but it is seldom used directly.
Understanding ILogger<T> It's a generic interface and if you say, go to the studio or the studio code create a new class which is using that interface, and then ask the IDE to pre-populate your class with the methods you need to implement because they are part of the interface.
ILogger and ILoggerFactory are dependencies that often require a lot of null checking, so they are perfect candidates for the null object pattern.
use a none generic ILogger in your base class, but ILogger<DerivedClass>
in your derived class. This way you can simply pass the ILogger to your base class if needed:
public abstract class BaseClassExample
{
private readonly ILogger logger;
public class BaseClassExample(ILogger logger)
{
this.logger = logger;
}
}
and
public class DerivedClass : BaseClassExample
{
private readonly ILogger<DerivedClass> logger;
public class BaseClassExample(ILogger<DerivedClass> logger)
:base(logger)
{
this.logger = logger;
}
}
this way not only you can use it easier if you somehow end up with two derived class you can use ILogger in both of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With