1

Possible Duplicate:
Help with Dependency Injection in .NET

Hi friends,

It is a couple of days that I've been seeing Dependency Injection in some websites !
Would you please say :

What is it ?
What's the benefits of using it ?

Thanks a lot.

Community
  • 1
  • 1
Mohammad Dayyan
  • 21,578
  • 41
  • 164
  • 232
  • This is a duplicate of http://stackoverflow.com/questions/743951/help-with-dependency-injection-in-net. – jason Jan 25 '10 at 14:12
  • Funny, the title is the same as the title of my book. Perhaps a web search could have helped you out... – Mark Seemann Jan 25 '10 at 14:22

2 Answers2

5

Dependency Injection is a very simple concept (the implementation, on the other hand, can be quite complex).

Dependency Injection is simply allowing the caller of a method to inject dependent objects into the method when it is called. For example if you wanted to allow the following piece of code to swap SQL providers without recompiling the method:

public void DoSomething()
{
    using(SQLConnection conn = new SQLConnection())
    {
        // Do some work.
    }
}

You could 'Inject' the SQL Provider:

public void DoSomething(ISQLProvider provider)
{
    // Do the work with provider
}

There's also Constructor Injection where you inject the dependency of an object during instanciation.

public class SomeObject
{
    private ISQLProvider _provider;

    public SomeObject(ISQLProvider provider)
    {
        _provider = provider;
    }
}

The whole point of Dependency Injection is to reduce coupling between the pieces of your application. The caller can substitute whatever it needs to get the job done without modifying the method it's calling (or the object it's creating).

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536