Must Dependency Injection come at the expense of Encapsulation?

后端 未结 21 2415
被撕碎了的回忆
被撕碎了的回忆 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:44

    Having struggled with the issue a little further, I am now in the opinion that Dependency Injection does (at this time) violate encapsulation to some degree. Don't get me wrong though - I think that using dependency injection is well worth the tradeoff in most cases.

    The case for why DI violates encapsulation becomes clear when the component you are working on is to be delivered to an "external" party (think of writing a library for a customer).

    When my component requires sub-components to be injected via the constructor (or public properties) there's no guarantee for

    "preventing users from setting the internal data of the component into an invalid or inconsistent state".

    At the same time it cannot be said that

    "users of the component (other pieces of software) only need to know what the component does, and cannot make themselves dependent on the details of how it does it".

    Both quotes are from wikipedia.

    To give a specific example: I need to deliver a client-side DLL that simplifies and hides communication to a WCF service (essentially a remote facade). Because it depends on 3 different WCF proxy classes, if I take the DI approach I am forced to expose them via the constructor. With that I expose the internals of my communication layer which I am trying to hide.

    Generally I am all for DI. In this particular (extreme) example, it strikes me as dangerous.

提交回复
热议问题