views:

44

answers:

2

Possible Duplicate:
What is dependency injection?

I've read the Wikipedia page. I've read an articulate explanation from a book from Apress.

I still don't understand what it is, or why it's useful.

StackOverflow seems to be the best place to ask this. :) Can an expert give me an easy to understand explanation?

+1  A: 

Dependency Injection means, in a nutshell, that you don't create the objects you need and you program against interfaces. By this, a class is easier to be tested, is much more independent of other code.

two examples:

First example:

using Core.Service.X;
using Core.Service.Y;

public class A //without injection
{
  private ServiceX servicex;
  private ServiceY servicey;

  public A ()
  {
    servicex = new ServiceX();
    servicey = new ServiceY();
  }
}

In this example, class A has to be aware of ServiceX and ServiceY and their implementation (this is a very simple example, ServiceX and ServiceY could have complex constructors themselves.

Second example:

using Core.ServiceInterfaces;

public class B //without injection
{
  private IServiceX servicex;
  private IServiceY servicey;

  public A (IServiceX serx, IServiceY, sery)
  {
    servicex = serx;
    servicey = sery;
  }
}

In this example, the class isn't aware of the specific implementation of either of the classes, it doesn't construct them itself. By this, the class is way more reuseable, as another party (normaly a DI-Container like Castle Windsor, Unity or MEF) takes care of the construction of these.

Femaref
@Femaref - you have a typo in second example. isn't it a DI ?
SoftwareGeek
A: 

Think of it as a configurable, declarative object factory. Instead of calling "new" to instantiate objects, the factory provides them for you.

Dependency injection demands a certain style of design (e.g., use of interfaces) that keeps your code layered and modular. It'll be easier to test, easier to modify by changing implementations rather than modifying code.

duffymo