Dependency Injection in .Net? [duplicate]

天大地大妈咪最大 提交于 2019-12-23 02:16:51

问题


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.


回答1:


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).




回答2:


Useful links :)

Dependency Injection on Wikipedia

Dependency Injection on Msdn

Simple tutorial on Dependency Injection



来源:https://stackoverflow.com/questions/2132772/dependency-injection-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!