Must Dependency Injection come at the expense of Encapsulation?

后端 未结 21 2417
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 05:21

If I understand correctly, the typical mechanism for Dependency Injection is to inject either through a class\' constructor or through a public property (member) of the clas

21条回答
  •  粉色の甜心
    2020-12-04 05:49

    It doesn't violate encapsulation. You're providing a collaborator, but the class gets to decide how it is used. As long as you follow Tell don't ask things are fine. I find constructer injection preferable, but setters can be fine as well as long as they're smart. That is they contain logic to maintain the invariants the class represents.

提交回复
热议问题