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
If you call out to your dependencies, you're actually doing work in a constructor.
From a client's perspective that is unexpected. When I do something like this:
var myObj = new SomeClass();
I don't expect any side-effects.
If you do things in the constructor, for example it could throw an exception, which is certainly not what you expect. It's like naming a method FetchUsers
and inside that method creating a user and returning it. Not what you'd expect.
There are several reasons for Nikola Malovic's 4th law of IoC:
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.