Normally when I need to inject one or more services into another service, I explicitly inject each one. However, I have a situation where injecting the service container itself will really make things easier. I know this is not a recommended practice, but I’m curious what the technical reasons are for discouraging this. Is it something legitimate like it’s too resource intensive, or a more personal feeling that it’s too messy?
Share
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…
…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…
…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.