依赖注入通过构造函数或属性设置器? [英] Dependency injection through constructors or property setters?

查看:117
本文介绍了依赖注入通过构造函数或属性设置器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这不是重复的。我做了一个搜索,但是有很多依赖注入的帖子,我在干草堆中找不到任何针。



所以这是我的问题。我正在重构一个类并添加一个新的依赖关系。该类目前正在构造函数中使用它现有的依赖项。所以为了一致性,我将参数添加到构造函数。



当然,有几个子类加上单元测试甚至更多,所以现在我正在玩游戏要改变所有的构造函数来匹配,并且需要时间。



这让我觉得使用setter的属性是获取依赖关系的更好方法。我不认为注入的依赖关系应该是构建类的实例的接口的一部分。你添加一个依赖项,现在所有的用户(子类和任何人直接实例化)突然知道它。这就像是封装的破裂。



但是,这似乎并不是现有代码的模式,所以我正在寻找一般共识是什么,构造函数与属性的优势+缺点。使用属性设置器更好吗?



编辑:哇,很多有用的答案在很短的时间内。看起来像构造函数的共识。

解决方案

嗯,这取决于: - )。



如果类无法执行其依赖关系的作业,则将其添加到构造函数中。类需要新的依赖关系,所以你希望你的改变来破解事情。另外,创建一个没有完全初始化的类(两步构造)是一个反模式(IMHO)。



如果类可以工作没有依赖一个设定者很好。


I hope this isn't a duplicate. I did a search but there are a lot of dependency injection posts and I couldn't find any needles in the haystack.

So here's my question. I'm refactoring a class and adding a new dependency to it. The class is currently taking its existing dependencies in the constructor. So for consistency, I add the parameter to the constructor.

Of course, there are a few subclasses plus even more for unit tests, so now I am playing the game of going around altering all the constructors to match, and it's taking ages.

It makes me think that using properties with setters is a better way of getting dependencies. I don't think injected dependencies should be part of the interface to constructing an instance of a class. You add a dependency and now all your users (subclasses and anyone instantiating you directly) suddenly know about it. That feels like a break of encapsulation.

But this doesn't seem to be the pattern with the existing code here so I am looking to find out what the general consensus is, pros + cons of constructors vs properties. Is using property setters better?

EDIT: Wow, lots of useful answers in a really short time. Looks like the consensus is for the constructor.

解决方案

Well, it depends :-).

If the class cannot do its job without the dependency, then add it to the constructor. The class needs the new dependency, so you want your change to break things. Also, creating a class that is not fully initialized ("two-step construction") is an anti-pattern (IMHO).

If the class can work without the dependency, a setter is fine.

这篇关于依赖注入通过构造函数或属性设置器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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