There have been several questions already posted with specific questions about dependency injection, such as when to use it and what frameworks are there for it. However,
What is dependency injection and when/why should or shouldn’t it be used?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Dependency Injection is passing dependency to other objects or framework( dependency injector).
Dependency injection makes testing easier. The injection can be done through constructor.
SomeClass()has its constructor as following:Problem: If
myObjectinvolves complex tasks such as disk access or network access, it is hard to do unit test onSomeClass(). Programmers have to mockmyObjectand might intercept the factory call.Alternative solution:
myObjectin as an argument to the constructormyObjectcan be passed directly which makes testing easier.It is harder to isolate components in unit testing without dependency injection.
In 2013, when I wrote this answer, this was a major theme on the Google Testing Blog. It remains the biggest advantage to me, as programmers not always need the extra flexibility in their run-time design (for instance, for service locator or similar patterns). Programmers often need to isolate the classes during testing.