为什么我不应该叫我依赖从构造方法中? [英] Why shouldn't I call my dependencies from within the constructor?

查看:166
本文介绍了为什么我不应该叫我依赖从构造方法中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为这是一个不好的做法,从构造函数中调用了一个班的依赖,但未能阐明为什么给同事昨天。任何人都可以不这样做提供了一个很好的理由。

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:

  • 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屋!

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