.NET中的依赖注入? [英] Dependency Injection in .Net?

查看:59
本文介绍了.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 ?

非常感谢。

推荐答案

依赖注入非常简单的概念(另一方面,实现可能非常复杂)。

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

依赖注入只是允许方法的调用者在调用方法时将依赖对象注入该方法。例如,如果您想允许以下代码交换SQL提供程序而无需重新编译该方法:

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

您可以注入 SQL Provider:

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

这篇关于.NET中的依赖注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆