首页 > 解决方案 > C#中的IOC和DI有什么区别以及为什么IOC优于其他设计模式

问题描述

总是在相同的上下文中读取 IOC(控制反转)和 DI(依赖注入)。IOC和DI之间到底有什么区别?IOC 与 DI 有何不同?以及 IOC 如何优于其他设计模式。

标签: c#dependency-injectioninversion-of-control

解决方案


可以在这里找到对 IoC 的一个很好的解释:tutorialteacher

所以用编码术语来设置它(这些只是粗略的例子,这里仅用于教育目的):

  1. 您的类执行一些业务逻辑并创建适当的对象来使用和实现它们。
public class Payment {
   public bool Execute(PaymentType type, decimal amount) {
        if (type == 1) {
            var payment = new PaymentService();
        } // etc
   }
}
  1. 通过应用 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
   }
}
  1. 通过使用 SOLID 原则中定义的 DIP(依赖倒置原则),您的类现在只期望抽象(接口)为它们完成工作。
public class Payment {
   public IPaymentService paymentService;
   public bool Execute(PaymentType type, decimal amount) {
        paymentService = PaymentServiceFactory.Create(type);
   }
}
  1. DI 现在将通过构造函数或参数注入为您的类提供(而不是工厂)正确的实现。

在此处输入图像描述


推荐阅读