Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inversion of Control (IoC / Dependency Injection) for Dummies [duplicate]

Possible Duplicate:
What is Inversion of Control?

Okay, I'm new to this site and I've seen that people is really willing to help, so imma take advantage of that and just ask another question if you don't mind.

So, I've readed a lot, I swear, BUT, I just can't seem to figure it out. WHAT in the world is Inversion of Control (IoC or Dependency Injection)? Why are ASP.NET MVC + Repository Pattern projects using it so much? And lastly, what they mean by "containers" and when they say "Inject my Controllers"?

I know it might be an old topic (or even a dumb question) but I just can't seem to get any for-dummies answers.

like image 502
Luis Aguilar Avatar asked Dec 19 '10 21:12

Luis Aguilar


2 Answers

Think of Dependency Injection/Inversion of Control as little more than a big object factory, a declarative, configuration-driven virtual constructor. Instead of littering your code with calls to "new" that hardwire the concrete type that your client class uses, you're now going to have that virtual constructor instantiate objects for you.

What's the advantage that all that complexity is buying you?

Object creation is now a declarative thing. If you happen to base your design on appropriate interfaces, you can ask the the object factory to create a proxy that implements the same interface when it's convenient. All kinds of good things are now possible: aspect-oriented programming, transparent remoting, declarative transactions, etc.

like image 60
duffymo Avatar answered Oct 29 '22 23:10

duffymo


Simple answer: It lets you hand in the "things" that any given object will use to do its work.

Contrived Example: Say the object wants to get the time for some purpose, you hand it a "ITimeService" and it calls "GetTime" on that.

The purpose of this is to "de-couple" the class from having hard relationships to things you may not wish it, and to aid testing.

In my humble opinion some people go a little overboard, but the testing argument is a valid one, and certainly it's an approach that is useful to adopt at times.

More involved answer: Martin Fowler on Inversion of Control.

like image 41
Noon Silk Avatar answered Oct 30 '22 01:10

Noon Silk