Do you find that dependency injection frameworks make code more difficult to follow? Does the indirection outweigh the benefit?
The main drawback of dependency injection is that using many instances together can become a very difficult if there are too many instances and many dependencies that need to be resolved.
Dependency Injection is a pattern, not any particular framework. You could even implement it manually, but that would be too much trouble.
So you should use dependency injection it would improve your code reuse and readability. You need to inject configuration data into one or more components. You need to inject the same dependency into multiple components. You need to inject different implementations of the same dependency.
Advantages. A basic benefit of dependency injection is decreased coupling between classes and their dependencies. By removing a client's knowledge of how its dependencies are implemented, programs become more reusable, testable and maintainable.
Yes, your code becomes much more decoupled and much more testable. This in particular becomes handy when you have lots of tests and each test requires a heavy object such as database layers.
If you use dependency injection, you can simply create so called 'mock' objects or stubs and use those to let your tests run more quickly and have less side effects (database state).
It is true that you cannot see directly which implementation is used by looking at the code. You will see a reference to the interface. A good IDE might have functionallity to view all implementations for a particular interface, so use that to your advantage.
For non-trivial "enterprisey" apps, yes it's worth it. Before DI frameworks, every shop implemented its own fancy "ServiceLocator" class in some internal library that their other projects used. So you had calls to that thing littered throughout the codebase.
Those calls represented the objects' need to discover/configure their own dependencies. The DI framework eliminates all that code, so your objects become simpler and therefore, easier to test.
Now, it follows that if you don't have a lot of variability in your objects' dependencies, the value of the indirection (the centralized configuration) is less for you.
For more details contrasting DI to ServiceLocator, see Fowler's Inversion of Control Containers and the Dependency Injection pattern
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With