[英]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第四定律有几个原因:
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.