Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base Class type for ILogger<T> using Dependency Injection

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?

like image 502
Chad K Avatar asked Feb 21 '20 18:02

Chad K


People also ask

What is ILogger category?

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.

What is ILogger T?

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.

Can ILogger be null?

ILogger and ILoggerFactory are dependencies that often require a lot of null checking, so they are perfect candidates for the null object pattern.


1 Answers

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.

like image 103
F_IVI_L Avatar answered Sep 21 '22 12:09

F_IVI_L