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:
  1. The dependency can be created, typically using the new operator.
  2. The dependency can be looked up by referring to a global variable.
  3. 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

Popular posts from this blog

Data Bound Controls in ASP.Net - Part 4 (FormView and DetailsView controls)

ASP.net: HttpHandlers

The Clickjacking attack and X-Frame-Options