c# - 如何将依赖项注入到通过从 startup.cs 中的 appsettings 绑定实例化的类中?
问题描述
我有一个辅助类,我在 startup.cs 中使用它来配置某些依赖项;当我需要使用它时,我一直在通过从 appsettings.json 中绑定一些值来获取它的一个实例。现在我想在其中注入一个记录器,但我无法弄清楚如何做到这一点。我知道我可以在构造函数中传入记录器,但我想知道是否有办法让它表现得像我的 api 控制器。我对这些如何实例化有点模糊。
在调用它之前,我尝试将类添加到服务中;没有骰子。无参数构造函数显然有效,但不提供依赖项。
//In startup.cs, ConfigureServices
//Pulling helper out of config and calling method
var value = Configuration.GetSection("Foo:Bar").Get<SomeClass>().SomeMethod();
//Example helper class
//SomeClass.cs
public class SomeClass
{
private readonly ILogger<SomeClass> _logger;
public SomeClass(ILogger<SomeClass> logger)
{
_logger = logger;
}
//properties
public string SomeMethod()
{
//do some stuff
//log results
return value;
}
}
记录器依赖项为空,或者它抱怨没有无参数构造函数。
解决方案
推荐阅读
- google-apps-script - Google 应用脚本 - 如何创建包含多张工作表的 excel 文件并附加到 MailApp?
- javascript - 在 Firebase 和 Javascript 中建立私人聊天
- javascript - 用户名条目在 mongodb nodejs 中都显示为“null”
- python - 如何为 tf.identity 计算梯度
- python - 错误:pyHook-1.5.1-cp37-cp37m-win_amd64.whl 不是该平台支持的滚轮
- python - Python 中使用 GPU 的并行逻辑回归 (MinPy)
- java - 如何添加两个包含十六进制数字的字符串而不将它们转换为 int?
- c# - C#计数并列出另一个方法的字典对
- swift - 如何在 UITextView 中动态加载图像
- angular - Ionic4 Firebase 加载数据时间过长