Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - 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 class 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 class BaseClassExample(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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...