为什么不注入IServiceProvider而不是注入每个依赖关系? [英] Why not inject IServiceProvider instead of each individual dependency?

查看:61
本文介绍了为什么不注入IServiceProvider而不是注入每个依赖关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么不通过单独注入每个依赖项来明确使用IServiceProvider来解决依赖项.换句话说,为什么要使用这种方法:

I am wondering why one wouldn't explicitly use the IServiceProvider to resolve dependencies over injecting each dependency individually. In other words, why use this approach:

public class A 
{
    private B _b;
    private C _c;
    private D _d;
    private E _e;

    public A(B b, C c, D d, E e)
    {
        _b = b;
        _c = c;
        _d = d;
        _e = e;
    }
}

不是这个:

public class A 
{
    private B _b;
    private C _c;
    private D _d;
    private E _e;

    public A(IServiceProvider sp)
    {
        _b = (b) sp.GetService(typeof(b));
        _c = (c) sp.GetService(typeof(c));
        _d = (d) sp.GetService(typeof(d));
        _e = (e) sp.GetService(typeof(e));
    }
}

请注意,我可能不会为所有类型调用 GetService ,某些类型实际上是可选的(即有时使用,有时不使用)

Note that I may not call GetService for all of the types, some of the types may be effectively optional (i.e. sometimes used, sometimes not used).

第二种方法的优点是,如果A的依赖项发生变化,我们不需要在调用A的构造函数的每个位置进行更改,而不必无论我们在哪里调用构造函数,所有依赖项都已经可用.

The advantage of the second approach being that we don't need to make a change in every place where we are calling the constructor of A if there is a change in the dependencies of A, and we don't need to have all of the dependencies already available wherever we are calling the constructor.

在以下文章中,MS似乎建议对此:

MS seems to recommend against this in the following article: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.2#recommendations They mention to avoid using the service locator pattern instead of DI, but aren't we still using DI here? Is the same thing not happening in the background anyway?

推荐答案

有几个原因.使用依赖项注入时,您将为DI容器负责为您准备依赖项.这些类不必在乎如何创建依赖项.如果切换到其他DI库,则必须在所有类中更改构造函数.

There are several reasons. When you use dependency injection, you are giving the DI container responsibility for preparing your dependencies for you. The classes shouldn't care about how your dependencies are created. If you switch to a different DI library you would have to change constructors in all of your classes.

另一个小问题是,您必须在每个单元测试中为服务容器创建一个模拟,这不是一个大问题,但肯定会令人讨厌.

Another small concern is that you would have to create a mock for your service container in every unit test which is not a huge issue but definitely something that could be annoying.

最后,当您必须将依赖项传递给嵌套类时,您的代码将变得非常奇怪,更不用说您希望继承了任何时候了.

Lastly your code will become very strange when you have to pass dependencies to nested classes, not to mention any time you want to have inheritance.

这篇关于为什么不注入IServiceProvider而不是注入每个依赖关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆