Search code examples
phpdependency-injectioninterfacearchitectureinversion-of-control

IoC in Domain Layer


In my Domain layer I have contract Hashing. One of my domain services depends on this contract. At the moment I have injected it within a __construct method.

In infrastructure layer I have implementation of this contract. I have written something looks like IoC container, which creates services with auto wiring injecting.

It all works. But I know that service's dependencies will grow up. I will add much more UseCases to them. And there is another one problem -- container injects all dependencies, but we could use only one UseCase, so it will do excess job.

Is it ok, if I will inject IoC container itself instead of many parameters, and use it in UseCases.

IoC contract also lies in Domain Layer contracts namespace


Solution

  • Is it ok, if I will inject IoC container itself instead of many parameters

    No, it is not okay. Supplying any class outside your Composition Root with access to an unbounded set of dependencies is considered an anti-pattern. This anti-pattern is called Service Locator.

    Injecting the container causes the class to take a dependency on a redundant component (the container) and makes it non-obvious what the class's dependencies are. This complicates testing and makes the class dishonest about its level of complexity.

    You might be tempted to inject the container to prevent the class's constructor from keep changing, but this is a sign of another problem. Classes that keep getting new dependencies likely violate the Single Responsibility Principle. You will end up with classes with many constructor arguments—a code smell called Constructor over-injection.