控制反转--就是把对象的依赖换成对抽象的依赖
步骤:抽象----实现----注册----使用
首先我们先添加接口项目和实现项目,再添加 ITestServiceA 接口类 和 TestServiceA 实现类

接口方法

实现接口和构造

注册

使用 创建 控制器和视图

生成编译 -> 运行
简单的IOC就完成了。
为什么要用IOC呢?
1. 可以去掉对细节的依赖,方便扩展---减小影响范围,甚至转移到配置文件依赖,只需要改配置文件
例如:很多控制器用到了 现在的 ITestServiceA ,那么我们要给 ITestServiceA 换一个实现类的话就很方便,只需要修改 Startup.cs ,把 TestServiceA 换成新的实现类就可以了,不用每个控制器去修改。

2.可以做到屏蔽细节,对象依赖注入(DI)
DI:构造对象时能自动把依赖的对象生成并传入,支持无限级递归。这种技术手段就叫依赖注入。
做个例子 ,添加多几个接口类,实现类 TestServiceB 构造时 依赖 TestServiceA,以此类推。TestServiceD 不依赖其他接口类。然后 TestServiceE 依赖 TestServiceC。



接着修改 Startup.cs

修改 控制器 IOCController.cs

生成编译 -> 运行
网友评论