views:

142

answers:

3

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.

+3  A: 

I suggest that you read this article.

klausbyskov
Thanks, I'll do it. But it was better if you posted some descriptions ;)
Mohammad
+1 for the speed :)
Madi D.
+2  A: 

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