ILogger< T>的基本类别类型使用依赖注入

编程入门 行业动态 更新时间:2024-10-11 15:16:29
本文介绍了ILogger< T>的基本类别类型使用依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个基类,可以完成一些工作,包括日志记录.我将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&lt; T&gt;的基本类别类型使用依赖注入

本文发布于:2023-11-13 23:02:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585561.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类别   类型   amp   ILogger   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!