Friday, January 25, 2019

c# - What is dependency injection and why would I want to use it?





Possible Duplicate:
What is dependency injection?





Other developers on my team keep talking about dependency injection. I have looked it up on Wikipedia but I still don't understand exactly what it is or when I would want to use it in my designs. If you have any good examples of when you have used it or when you shouldn't that would really help me out. Thanks


Answer



The basic idea is that when an object needs some other other to do it's work (say for example, a database connection), instead of creating that object internally, the object is "injected" into the object, usually either as a constructor parameter, or by a public property that is set before the object is used.



The advantage of that is that the value of the used object can be changed externally (this is especially true if the object is declared as an interface). One common use of this is to replace concrete object with mock object for unit testing.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...