ILogger<T> 的基类类型使用依赖注入 [英] Base Class type for ILogger<T> using Dependency Injection
问题描述
我有一个基类可以做一些工作,包括日志记录.我有一个 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
.通过这种方式,您可以根据需要简单地将 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> 的基类类型使用依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!