为什么我不应该叫我依赖从构造方法中? [英] Why shouldn't I call my dependencies from within the constructor?
本文介绍了为什么我不应该叫我依赖从构造方法中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直认为这是一个不好的做法,从构造函数中调用了一个班的依赖,但未能阐明为什么给同事昨天。任何人都可以不这样做提供了一个很好的理由。
I've long considered it a bad practice to call out to a classes dependencies from within the constructor but wasn't able to articulate why to a colleague yesterday. Can anyone provide a good reason for NOT doing this?
推荐答案
有几个原因尼古拉Malovic的的4th法国际奥委会:
There are several reasons for Nikola Malovic's 4th law of IoC:
- 当我们撰写与构造器注入我们经常创造丰厚的对象图,应用程序,我们希望能够< A HREF =http://blog.ploeh.dk/2011/03/04/Composeobjectgraphswithconfidence>尽可能有效地的创建这些图。这是尼古拉的原始说法。
- 在,你有循环依赖奇(不推荐)的情况下,注入的依赖可能还没有完全初始化,所以试图在调用其成员那时可能会导致异常。这个问题类似于从构造函数调用虚拟成员问题。从概念上讲,注入的依赖相当于一个虚拟的成员。
- 通过构造函数注入,构造函数的责任是需求和接收的依赖关系。因此,根据单一职责原则(SRP),它不应该尝试做别的事情为好。有些读者可能会说,我在这里滥用SRP,但我觉得我只是运用的基本原则在更精细的内容。
- When we compose applications with Constructor Injection we often create substantial object graphs, and we want to be able to create these graphs as efficiently as possible. This is Nikola's original argument.
- In the odd (and not recommended) cases where you have circular dependencies, the injected dependencies may not yet be fully initialized, so an attempt to invoke their members at that time may result in an exception. This issue is similar to the issue of invoking virtual members from the constructor. Conceptually, an injected dependency is equivalent to a virtual member.
- With Constructor Injection, the constructor's responsibility is to demand and receive the dependencies. Thus, according to the Single Responsibility Principle (SRP), it should not try to do something else as well. Some readers might argue that I'm misusing the SRP here, but I think I'm simply applying the underlying principle in a more granular context.
请注意,这个规则是语境:它适用于使用Constructor注入服务。实体和值对象倾向于不使用DI,所以它们的构造是由其他规则覆盖。
Please notice that this rule is contextual: it applies to Services that use Constructor Injection. Entities and Value Objects tend not to use DI, so their constructors are covered by other rules.
这篇关于为什么我不应该叫我依赖从构造方法中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文