Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection Frameworks: How do they work?

I consider myself an experienced programmer and understand the basic concept of dependency injection. On the other hand, most of my experience is in writing relatively low-level, one-man number crunching code. I have no experience whatsoever working on large enterprise projects.

Given this background, I can't for the life of me wrap my head around why anyone would need a framework to do dependency injection. Can someone give me a brief overview of how such a framework works, without getting into lots of specifics, and explain how it makes life easier than just rolling your own?

Edit: I've gotten some great answers here. Am I correct in saying that a DI framework basically gives you a convenient way to create globally accessible factories that create/return instances of dependencies whenever an object requests them? If so, I've been doing stuff like this in very ad-hoc ways in my code all along, but never thought to use any kind of formal/heavyweight framework for it.

like image 270
dsimcha Avatar asked Oct 19 '10 23:10

dsimcha


People also ask

How does dependency injection framework work?

A DI framework will normally provide both object creation facilities (figure out the dependencies required for the constructor) as well as a Service Locator facility so that not everything has to be passed in the constructor or as a parameter to methods.

Why do we need a dependency injection framework?

We should use the dependency framework because of the following: It helps us in managing the complex dependencies easily. It makes the unit testing easy by enabling us to pass all the dependencies from outside so that we can easily use the mocked objects. It easily manages the scope(lifecycle) of the object.

How does DI work?

DI is a process whereby objects define their dependencies. The other objects they work with—only through constructor arguments or arguments to a factory method or property—are set on the object instance after it is constructed or returned from a factory method.


1 Answers

DI is all about decoupling dependencies between classes.

With DI, your classes no longer have references to implementing classes. The factory pattern comes close to DI, but it’s different because a factory class is it selves a unwanted dependency (that for example will hurt unit testing).

DI is also not necessarily a global or application wide affair; it’s possible to configure different dependency schema’s for the same application and the same classes. There can even be runtime dependencies. DI can even determine the lifecycle or scope in which objects need to live (request scope, session scope, etc.).

It is also not heavy weight or intrusive, if you look at lightweight DI implementations like Google’s Guice. It’s not for nothing they call it the new “new”.

like image 153
Kdeveloper Avatar answered Nov 18 '22 05:11

Kdeveloper