What are the technical reasons to avoid injecting the service container instead of individual services? What are the technical reasons to avoid injecting the service container instead of individual services? symfony symfony

What are the technical reasons to avoid injecting the service container instead of individual services?


If you inject the container, you're not making dependencies clear. In fact, you're obscuring them more than before. If you have a class like this...

class DocumentCreator(IFileNamer fileNamer, IRepository repository){ ... }

...you can see what the dependencies are. You can also easily mock those dependencies for unit testing, to ensure that you isolate the DocumentCreator and can know that any test failures are a result of its code rather than code in one of its dependencies.

If, on the other hand, you do this...

class DocumentCreator(IDependencyContainer container){ ... }

...you've obscured the dependencies. You can't know, without examining the internals of the class, that it requires an IFileNamer and an IRepository.

Nor can you easily know what mocks you need to put in the container in order to test DocumentCreator. Mocking the IDependencyContainer won't help you at all; your class will still fail in testing because the container won't contain an IFileNamer and an IRepository, unless you examine the internals of the class to see that they're required.


What you describe is a ServiceLocator. This is considered an anti-pattern in modern application design. This article describes why.


I think the main problem with this approach is that you don't see the dependencies clearly anymore. Another problem might be that it is more difficult to test.