首页 > 解决方案 > 如何将依赖项注入到通过从 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;
    }
}

记录器依赖项为空,或者它抱怨没有无参数构造函数。

标签: c#dependency-injectionconfiguration

解决方案


推荐阅读