如何从嵌套类通过依赖注入服务进行访问?

Ант*_*дин 1 c# dependency-injection asp.net-core

假设我有这段代码(一般而言),假设我需要在 C 类中使用 ILogger,而在 A 类和 B 类中不需要它

public class A
{
    var classB = new B();
}
public class B
{
    var classC = new C();
}
public class C
{
    //Here I want to use the Ilogger service
}
Run Code Online (Sandbox Code Playgroud)

但沿着这整条链条传递构造函数似乎不合理,而且随着使用的服务的增加,构造函数只会增长。那么如何正确调用C类的服务呢?谢谢

Nei*_*ell 5

如果您正在进行依赖注入,您别无选择,只能将 的实现传递ILogger给每个新的C. 这是有问题的,因为如果一个类需要创建一个新的C,那么它又ILogger从哪里获取实现并传入?这个问题随着每一个决定它需要的类而增长ILogger

答案通常是使用控制反转容器,例如现在内置于 .NET 中的容器,或其他容器(Castle Windsor、Autofac 等)。在这种情况下,A不会B直接调用构造函数。相反,B将取决于C并且A将取决于B。IoC 容器将创建整个对象图,并根据需要填充所有依赖项。

public class A : IA
{
    private IB _b;

    public A(IB b)
    {
        _b = b;
    }
}

public class B : IB
{
    private IC _c;

    public B(IC c)
    {
        _c = c;
    }
}

public class C : IC
{
    private ILogger _logger;

    public B(ILogger logger)
    {
        _logger = logger;
    }
}
Run Code Online (Sandbox Code Playgroud)

别的地方:

// Assuming A, B, C, and ILogger have all been registered with the container:
var a = Container.Resolve<IA>();
Run Code Online (Sandbox Code Playgroud)