Why shouldn't I call my dependencies from within the constructor?

前端 未结 2 535
予麋鹿
予麋鹿 2021-01-13 08:40

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 a

2条回答
  •  悲哀的现实
    2021-01-13 09:39

    There are several reasons for Nikola Malovic's 4th law of IoC:

    • When we compose applications with Constructor Injection we often create substantial object graphs, and we want to be able to create these graphs as efficiently as possible. This is Nikola's original argument.
    • In the odd (and not recommended) cases where you have circular dependencies, the injected dependencies may not yet be fully initialized, so an attempt to invoke their members at that time may result in an exception. This issue is similar to the issue of invoking virtual members from the constructor. Conceptually, an injected dependency is equivalent to a virtual member.
    • With Constructor Injection, the constructor's responsibility is to demand and receive the dependencies. Thus, according to the Single Responsibility Principle (SRP), it should not try to do something else as well. Some readers might argue that I'm misusing the SRP here, but I think I'm simply applying the underlying principle in a more granular context.

    Please notice that this rule is contextual: it applies to Services that use Constructor Injection. Entities and Value Objects tend not to use DI, so their constructors are covered by other rules.

提交回复
热议问题