简单C#中的DI和IOC示例 [英] DI and IOC examples in simple C#

查看:404
本文介绍了简单C#中的DI和IOC示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

控制反转<依赖注入

有人可以用简单的C#来帮助我理解DI和IOC吗?请举个例子吗?据我了解,IOC是控制流的倒置(对我而言这毫无意义),而DI则意味着通过属性或构造函数注入接口。不确定这两者之间的关系。

Could anyone please help me to understand DI and IOC with simple C# example please? As I understand IOC is the inversion of control flow (which means nothing to me) and DI means injecting interfaces via properties or constructors. Not sure how these two are related.

谢谢。

推荐答案

我将添加一种解释,告诉我这是一个有用的解释。

I'll add an explanation that I've been told is a helpful one.

正如您正确指出的那样,依赖注入是类通过构造函数或setter注入要求其协作者的行为。您可以将其视为一种编码技术。另一方面,控制反转更多地是一种设计技术,一种哲学。

As you correctly point out, dependency injection is the act of a class demanding its collaborators via constructor or setter injection. You could think of this as a coding technique. Inversion of control, on the other hand, is more of a design technique -- a philosophy, if you will.

在过程编程中(以及OO中的过程样式编程)语言),您通常会有某种命令和控制的哲学。如果您要创建一个由三个楼层对象组成的房屋对象,每个房屋对象都由一定数量的房间对象组成,那么您将创建一个房屋对象,其构造函数实例化三个楼层对象,每个对象的构造函数又实例化房间对象。

In procedural programming (and procedural-style programming in OO languages), you generally have some kind of "command and control" philosophy. If you're creating a house object that consists of three floor objects, which consist of some number of room objects each, you create a house object whose constructor instantiates three floor objects, each of whose constructor, in turn, instantiates room objects.

反转控制时,就是在反转命令和控制范式。使用IoC,当我实例化房屋时,它并不会为我处理所有细节。相反,它说,通过其构造函数(和依赖项注入),如果没有一些限制,您无法实例化我。因此,您去实例化地板,然后他们说不,不是没有一些房间。现在,以这种倒置风格,我们的房子无法控制房间的创建-它由其他人来决定,而是只表达给定房间的意义。之所以需要这样做,是因为通过翻转其顶部的命令和控制,您可以更好地进行推理和测试代码-将内容分解为组件更容易。

When you invert control, you're inverting command and control paradigm. With IoC, when I go to instantiate a house, it doesn't take care of all of its details for me. Instead, it says, via its constructor (and dependency injection), "you can't instantiate me without some floors". So, you go to instantiate the floors and they say "nope, not without some rooms". Now, in this "inverted" style, our house doesn't control the creation of the rooms - it leaves that up to someone else and it expresses instead, only what it will do with the rooms it's given. This is desirable because, by flipping command and control on its head, you have better seams for reasoning about and testing the code -- it's easier to deconstruct things into components.

因此,总而言之,控制反转是哲学,依赖注入是实现控制的手段。

So, to summarize, inversion of control is the philosophy and dependency injection is the means by which it's achieved.

这篇关于简单C#中的DI和IOC示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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