简体   繁体   中英

Dependency injection container? What does it do?

I have been reading up on DI and it seems like a simple enough concept. What I don't get is the container. Let's say for a moment that I want to create my own container. Verbs like "detect" are used and I don't get how the container "detects" that a new dependent object was created and know to inject it's dependencies. To me it seems like the container is a glorified factory.

Can any one explain how a container is actually implemented, or maybe point me to a resource?

Thank you!

This is taken from Windsor documentation

Inversion of Control

Inversion of Control is a principle used by frameworks as a way to allow developers to extend the framework or create applications using it. The basic idea is that the framework is aware of the programmer's objects and makes invocations on them.

This is the opposite of using an API, where the developer's code makes the invocations to the API code. Hence, frameworks invert the control: it is not the developer code that is in charge, instead the framework makes the calls based on some stimulus.

You have probably been in situations where you have developed under the light of this principle, even though you were not aware of it.

Inversion of Control Container

An Inversion of Control Container uses the principle stated above to (in a nutshell) manage classes. That is, their creation, destruction, lifetime, configuration, and dependencies. This way classes do not need to obtain and configure the classes they depend on. This dramatically reduces coupling in a system and, as a consequence, simplifies reuse and testability.

There is some confusion created by people that think that 'Inversion of Control' is a synonym for 'Inversion of Control Container'. As stated, Inversion of control is a broader principle.

Often people think that it is all about "injection", and broadcast that this is the primary purpose of IoC containers. In fact, "injection" is a consequence, a means to decouple, not the primary purpose.

You might wanna read this book Dependency Injection In .NET ... I have already read it, and I strongly recommend you reading it. It first gives a nice and insightful explanation on DI then shows code and patterns about real world applications of DI.

From this book, and in too few words...

"DI container is the technology used to support the DI technique" Page 55

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM