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

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

问题描述

我正在重构一个类并向它添加一个新的依赖项.该类目前正在构造函数中获取其现有的依赖项.所以为了一致性,我将参数添加到构造函数中.
当然,还有一些子类以及用于单元测试的更多子类,所以现在我正在玩游戏,改变所有构造函数以匹配,这需要很长时间.
这让我认为将属性与 setter 一起使用是获取依赖项的更好方法.我认为注入的依赖项不应该是构造类实例的接口的一部分.您添加了一个依赖项,现在您的所有用户(子类和任何直接实例化您的人)突然都知道了.这感觉就像打破了封装.

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.

这似乎不是这里现有代码的模式,所以我想找出普遍的共识,构造函数与属性的优缺点.使用属性设置器更好吗?

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 and cons of constructors versus properties. Is using property setters better?

推荐答案

好吧,这取决于:-).

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).

如果类可以在没有依赖的情况下工作,那么 setter 就可以了.

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

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

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