2

Possible Duplicate:
What is dependency injection?

Im learning asp.net mvc 3. One of the new features being Dependency Injection. Can someone tell me what it is? why is it useful? and when to use it? Thanks

Community
  • 1
  • 1
Jason
  • 61
  • 1
  • 7
  • 3
    duplicate of [What is dependency injection?](http://stackoverflow.com/questions/130794/what-is-dependency-injection) – John Farrell Jan 14 '11 at 05:36

3 Answers3

6

Dependency injection is the process by which dependencies are provided to consuming code rather than that code being responsible for instantiating the objects themselves. In a primitive example you may have a class that is responsible for calculating an invoice for services rendered. You instansiate it and call its 'Calculate' method:

public class InvoiceBiller
{
    public void Bill()
    {
        Calculator calculator = new Calculator();
        var totalAmountDue = calculator.CalculateBill(hoursWorked);
    }
}

This method is dependent on the Calculator class. That's fine, it works. However depenedency injection would have you "inject" the Calculator dependency:

public class InvoiceBiller
{
    private readonly Calculator calculator;

    public InvoiceBiller(Calculator calculator)
    {
        this.calculator = calculator;
    }

    public void Bill()
    {
        var totalAmountDue = calculator.CalculateBill(hoursWorked);
    }
}

As you can see in the second example the InvoiceBiller class is given a Calculator object through its constructor (a form of dependency injection called constructor injection). The InvoiceBiller is no longer concerned with how to get an instance of the biller, it is simply given one.

This helps in testing. You can pass in whatever instance of Calculator you want from your tests. At runtime in the real product you may pass in a calculator that is connected to the database and looks up hourly rates. For testing you pass in a calculator that uses hard coded rates so that your tests don't need to hit the database.

Taking this a step further, you generally pass in an interface instead of a concrete type:

public class InvoiceBiller
{
    private readonly ICalculator calculator;

    public InvoiceBiller(ICalculator calculator)

Now you're programming against interfaces not implementation. Again from your tests you can use mocking frameworks to create mocks of your interface type and pass them to the class.

Michael Shimmins
  • 19,511
  • 7
  • 54
  • 90
3

In fact, there are two questions in here. There is "What is Dependency Injection?" and "What is new in MVC 3 that 'adds more' Dependency Injection support?".

Dependency Injection is a programming pattern when classes do not define new objects of other classes before they use them (like Some Email Sender class that needs to log emails in DB wouldn't create new instance of Logger), but request it to be provided without knowing even which class it might be (using an interface, say ILogger in our case). The logger here would be a dependency and this dependency is requested / injected, by many ways, either being requested as a constructor parameter of the dependent class (EmailSender for example), or just making it a property on the class "set" accessor, etc...

There are some libraries called Dependency Injection libraries, or Inversion Of Control Container. Those are libraries where you define which classes should be used really in runtime and which other specific values to be used, and tell them to create the objects for you (like create instance of EmailSender) passing all the dependencies to them, recursively (so, if ILogger is actually a DBLogger that needs connection string, it sends it too, etc..). examples are Windsor, Ninject, Autofac, Microsoft Unity, ...

For sample code and more clear example, see this nice free video from a guy who used to work in ASP.NET MVC team:
http://tekpub.com/view/concepts/1

ASP.NET MVC always allowed a factory class where you can override how the Controller class is created (so that you can use the DI container library to create the controller and its dependencies, as if it was or EmailSender class). What came in ASP.NET MVC 3.0 was improvements over the existing functionality and providing more methods like it so that it's easier to do DI all over ASP.NET MVC

and

Check them out for deep details...

Community
  • 1
  • 1
Meligy
  • 32,897
  • 11
  • 79
  • 103
2

Probably more suited for Programmers, but first learn about Inversion of Control

http://en.wikipedia.org/wiki/Inversion_of_control

http://www.martinfowler.com/articles/injection.html

The idea is that a component should not know about how to get/create its dependencies, it should be provided what it needs to get the job done.

Vadim
  • 17,547
  • 4
  • 36
  • 62