When will you use dependency injection? Is there any overwhelming benefit of using dependency injection?
To implement the IoC, you have the choice of two main patterns: Service Locator and Dependency Injection. The Service Locator allows you to "resolve" a dependency within a class and the Dependency Injection allows you to "inject" a dependency from outside the class.
More specifically, dependency injection is effective in these situations: 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.
Service Locator is a well-known pattern, and since it was described by Martin Fowler, it must be good, right? No, it's actually an anti-pattern and should be avoided.
A registry pattern has no control over the lifetime of the instances, but injecting a DI container into the application gives the DI container explicit control over the instance lifetimes. The latter can give each type a different lifetime, the former are always singleton lifetime regardless of the type requested.
Fowler has good comparision between the two in his Inversion of Control Containers and the Dependency Injection pattern Heading. In his concluding thoughts, he says
Dependency Injection is a useful alternative to Service Locator. When building application classes the two are roughly equivalent, but I think Service Locator has a slight edge due to its more straightforward behavior. However if you are building classes to be used in multiple applications then Dependency Injection is a better choice.
You can find more view points and comparisons in here
For DI:
Against DI:
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