开发者

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

This question already has answers here: Closed 12 years ago.

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 Con开发者_运维问答trol (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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜