Friday 25 January 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...