什么是控制反转(IoC)? [英] What is Inversion of Control (IoC)?

查看:151
本文介绍了什么是控制反转(IoC)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以指导我一些有关控制反转(IoC)的基础教程吗? (最好是.net/c#).

Can someone guide me to some basic tutorials on inversion of control (IoC)? (preferably .net/c#).

我需要一些动手操作的代码才能绕开它:)

I need some hands on code to wrap my head around it :)

推荐答案

在大多数应用中,IOC(即控制权倒置)正在将通过代码的路径从UI转换为数据库.这不是一个完整的答案,但这是让您深入了解这一概念的最简单方法之一.

IOC, or inversion of control, is, in most apps, inverting the route through the code from UI to database. This si not a complete answer, but it is one of the easiest ways to get your head around the concept.

如果您想学习IOC,请进入TDD,因为一旦您求反,您会发现设置测试要容易得多.

If you want to learn IOC, get into TDD, as you will find setting up tests a lot easier once you invert.

示例:

我见过的大多数.NET应用程序的典型流程是这样的:

Typical flow of most .NET apps I have seen is something like this:

UserCollection col = BusinessLayer.Class.GetLoggedInUsers();
//Business logic
return col;

那么生意是这样的:

UserTable table = DataLayer.Class.GetLoggedInUsers();
return table;

等这都是伪代码.要在此示例中使用IOC,请为数据层类添加一个接口,例如IUserRepository.您可以使用泛型,我建议在引擎盖下.

etc. This is all pseudocode. To use IOC in this example, you add an interface for the data layer class, like IUserRepository. You can use generics, and I would recommend underneath the hood.

然后您可以执行以下操作:

You can then do something like this:

IUserRepository repository = SetUpRepository();
UserCollection col = BusinessLayer.Class.GetUsers(repository);

为什么这很重要?为了进行测试,您可以创建一个模拟存储库,并将其提供给业务类.该模拟包含的数据始终相同,这意味着您正在执行代码,而不是端到端进行测试.

Why is this important? For testing, you can create a mock repository and feed it to the business class. The mock contains data that is always the same, which means you are exercising your code, not testing end to end.

如果要使用C#,请参见

If you want C#, here is a basic example on weblogs.asp.net :

这篇关于什么是控制反转(IoC)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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