我有一个基类,可以完成一些工作,包括日志记录.我将ILogger依赖项注入到构造函数中
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; } }我想让类实现BaseClassExample,并做自己的工作,还包括日志记录.
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; } }这是正确的做事方式吗?我是否应该获取实现类的类型以记录基类?我应该使用记录器的单独实例(具有DerivedClass的类型)还是尝试使用与基类相同的记录器?
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?
推荐答案在基类中使用非通用ILogger,但在派生类中使用 ILogger< DerivedClass> .这样,您就可以根据需要简单地将ILogger传递给您的基类:
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; } }和
public class DerivedClass : BaseClassExample { private readonly ILogger<DerivedClass> logger; public class BaseClassExample(ILogger<DerivedClass> logger) :base(logger) { this.logger = logger; } }这样,如果您以某种方式最终得到两个派生类,则不仅可以更轻松地使用它,还可以在两个派生类中使用ILogger.
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.
更多推荐
ILogger< T>的基本类别类型使用依赖注入
发布评论