简体   繁体   English

为什么我不应该在构造函数中调用我的依赖项?

[英]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? 任何人都可以提供不这样做的充分理由吗?

There are several reasons for Nikola Malovic's 4th law of IoC : Nikola Malovic的IoC第四定律有几个原因:

  • 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 . 当我们使用Constructor Injection组合应用程序时,我们经常创建实质的对象图,并且我们希望能够尽可能高效创建这些图 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. 因此,根据单一责任原则(SRP),它不应该尝试做其他事情。 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. 有些读者可能会说我在这里滥用SRP,但我认为我只是在更细化的背景下应用基本原则。

Please notice that this rule is contextual: it applies to Services that use Constructor Injection. 请注意, 此规则是上下文的:它适用于使用Constructor Injection的服务。 Entities and Value Objects tend not to use DI, so their constructors are covered by other rules. 实体和值对象倾向于不使用DI,因此其构造函数受其他规则的约束。

If you call out to your dependencies, you're actually doing work in a constructor. 如果你调用你的依赖项,你实际上是在构造函数中工作。

From a client's perspective that is unexpected. 从客户的角度来看是出乎意料的。 When I do something like this: 当我做这样的事情时:

var myObj = new SomeClass();

I don't expect any side-effects. 我不指望任何副作用。

If you do things in the constructor, for example it could throw an exception, which is certainly not what you expect. 如果您在构造函数中执行某些操作,例如它可能会抛出异常,这肯定不是您所期望的。 It's like naming a method FetchUsers and inside that method creating a user and returning it. 这就像命名方法FetchUsers并在该方法中创建用户并返回它。 Not what you'd expect. 不是你所期望的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM