Dependency injection
In this post, we will look at Dependency Injection.
Dependency Injection (DI) is a software design pattern that deals with how code gets hold of its dependencies.
There are only three ways an object or a function can get a hold of its dependencies:
Dependency injection is basically providing the objects that an object needs instead of having it construct them itself.
Do this:
Instead of this:
Dependency Injection (DI) is a software design pattern that deals with how code gets hold of its dependencies.
There are only three ways an object or a function can get a hold of its dependencies:
- The dependency can be created, typically using the
new
operator. - The dependency can be looked up by referring to a global variable.
- The dependency can be passed in to where it is needed.
Dependency injection is basically providing the objects that an object needs instead of having it construct them itself.
Do this:
public SomeClass (MyClass myObject) {
this.myObject = myObject;
}
Instead of this:
public SomeClass() {
myObject = Factory.getObject();
}
Dependencies can be injected into objects by many means. One can even
use specialized dependency injection frameworks to do that, but they
certainly aren't obligatory. You don't need those frameworks to have
dependency injection. Instantiating and passing objects (dependencies)
explicitly to is just as good an injection as injection by a framework.
It's a very useful technique for testing, since it allows
dependencies to be mocked or stubbed out. Dependency Injection is typically used in controllers and factory methods.
Comments
Post a Comment