c# - C#中的IOC和DI有什么区别以及为什么IOC优于其他设计模式
问题描述
总是在相同的上下文中读取 IOC(控制反转)和 DI(依赖注入)。IOC和DI之间到底有什么区别?IOC 与 DI 有何不同?以及 IOC 如何优于其他设计模式。
解决方案
可以在这里找到对 IoC 的一个很好的解释:tutorialteacher
所以用编码术语来设置它(这些只是粗略的例子,这里仅用于教育目的):
- 您的类执行一些业务逻辑并创建适当的对象来使用和实现它们。
public class Payment {
public bool Execute(PaymentType type, decimal amount) {
if (type == 1) {
var payment = new PaymentService();
} // etc
}
}
- 通过应用 IoC,工厂将负责创建适当的对象来完成工作
public class Payment {
public bool Execute(PaymentType type, decimal amount) {
var payment = PaymentServiceFactory.Create(type);
}
}
public class PaymentServiceFactory {
public static PaymentService Create(PaymentType type) {
if (type == 1) {
return new PaymentService();
} // etc
}
}
- 通过使用 SOLID 原则中定义的 DIP(依赖倒置原则),您的类现在只期望抽象(接口)为它们完成工作。
public class Payment {
public IPaymentService paymentService;
public bool Execute(PaymentType type, decimal amount) {
paymentService = PaymentServiceFactory.Create(type);
}
}
- DI 现在将通过构造函数或参数注入为您的类提供(而不是工厂)正确的实现。
推荐阅读
- sql - 在不同条件下两次加入同一张表
- python - OperationalError:没有这样的列,但列在任何地方都不存在
- unix - 使用 Unix 脚本从 ftp 上传和下载文件
- php - 我的 php 代码显示为文本并且不会运行
- git - 我可以制作单个 repo git push 可执行文件吗?
- php - 致命错误:在 LAMP 堆栈上使用 Docker 组合未捕获的 PDO 异常
- r - 从多个数据帧中提取同一列并将它们绑定到 R 中的新数据帧中
- python - Pandas 对 multindex 进行什么样的合并、连接或连接
- python - 如何在 sqlalchmey 中编写 Lead() 函数?
- php - 如何计算每个用户的喜欢并获得顶级用户的喜欢?