根据Martin Fowler所写的论文,控制反转是程序控制流反转的原理:由外部源(框架、服务、其他组件)控制程序流,而不是由程序员控制程序流。就像我们把一个东西插入另一个东西。他提到了一个关于EJB 2.0的例子:

例如,会话Bean接口 定义ejbRemove, ejbPassivate (存储到二级存储),以及 ejbActivate(从被动恢复 状态)。你不能控制时间 这些方法被调用,只是什么 他们做的事。集装箱召唤我们,我们 别这么说。

这就导致了framework和library的区别:

控制反转是一个关键的部分 框架与框架的区别是什么 图书馆。图书馆本质上是一个 一组你可以调用的函数, 这些日子通常组织成 类。每次调用都要做一些工作 将控制权返回给客户端。

我认为,DI是IOC的观点,意味着对象的依赖关系是倒置的:而不是它控制自己的依赖关系、生命周期……其他东西可以帮你。但是,正如你告诉我的DI by hands, DI不一定是IOC。我们仍然可以有DI,没有IOC。

然而,在本文中(来自pococapsule, C/ c++的另一个IOC框架),它指出,由于IOC和DI, IOC容器和DI框架要比J2EE优越得多,因为J2EE将框架代码混合到组件中,因此它不是普通的旧Java/ c++对象(POJO/POCO)。

依赖注入模式以外的控制反转容器(存档链接)

附加阅读,了解旧的基于组件的开发框架的问题,这导致了上面的第二篇论文:为什么和什么反转控制(档案链接)

我的问题:IOC和DI到底是什么?我很困惑。基于pococapsule, IOC不仅仅是对象或程序员与框架之间控制的反转。


当前回答

因为所有的答案都强调理论,我想用一个例子优先的方法来证明:

假设我们正在构建一个应用程序,该应用程序包含在订单发出后发送SMS确认消息的功能。 我们将有两个类,一个负责发送SMS (SMSService),另一个负责捕获用户输入(UIHandler),我们的代码如下所示:

public class SMSService
{
    public void SendSMS(string mobileNumber, string body)
    {
        SendSMSUsingGateway(mobileNumber, body);
    }

    private void SendSMSUsingGateway(string mobileNumber, string body)
    {
        /*implementation for sending SMS using gateway*/
    }
}

public class UIHandler
{
    public void SendConfirmationMsg(string mobileNumber)
    {
        SMSService _SMSService = new SMSService();
        _SMSService.SendSMS(mobileNumber, "Your order has been shipped successfully!");
    }
}

Above implementation is not wrong but there are few issues: -) Suppose On development environment, you want to save SMSs sent to a text file instead of using SMS gateway, to achieve this; we will end up changing the concrete implementation of (SMSService) with another implementation, we are losing flexibility and forced to rewrite the code in this case. -) We’ll end up mixing responsibilities of classes, our (UIHandler) should never know about the concrete implementation of (SMSService), this should be done outside the classes using “Interfaces”. When this is implemented, it will give us the ability to change the behavior of the system by swapping the (SMSService) used with another mock service which implements the same interface, this service will save SMSs to a text file instead of sending to mobileNumber.

为了解决上述问题,我们使用接口,这些接口将由我们的(SMSService)和新的(MockSMSService)实现,基本上新接口(ISMSService)将公开两个服务的相同行为,如下所示:

public interface ISMSService
{
    void SendSMS(string phoneNumber, string body);
}

然后我们将改变我们的(SMSService)实现来实现(ISMSService)接口:

public class SMSService : ISMSService
{
    public void SendSMS(string mobileNumber, string body)
    {
        SendSMSUsingGateway(mobileNumber, body);
    }

    private void SendSMSUsingGateway(string mobileNumber, string body)
    {
        /*implementation for sending SMS using gateway*/
        Console.WriteLine("Sending SMS using gateway to mobile: 
        {0}. SMS body: {1}", mobileNumber, body);
    }
}

现在我们将能够创建新的模拟服务(MockSMSService),使用相同的接口使用完全不同的实现:

public class MockSMSService :ISMSService
{
    public void SendSMS(string phoneNumber, string body)
    {
        SaveSMSToFile(phoneNumber,body);
    }

    private void SaveSMSToFile(string mobileNumber, string body)
    {
        /*implementation for saving SMS to a file*/
        Console.WriteLine("Mocking SMS using file to mobile: 
        {0}. SMS body: {1}", mobileNumber, body);
    }
}

在这一点上,我们可以更改(UIHandler)中的代码来使用服务(MockSMSService)的具体实现,如下所示:

public class UIHandler
{
    public void SendConfirmationMsg(string mobileNumber)
    {
        ISMSService _SMSService = new MockSMSService();
        _SMSService.SendSMS(mobileNumber, "Your order has been shipped successfully!");
    }
}

我们已经实现了很大的灵活性,并在代码中实现了关注点分离,但是我们仍然需要在代码基础上做一些更改,以便在两个SMS服务之间切换。所以我们需要实现依赖注入。

为了实现这一点,我们需要对(UIHandler)类构造函数进行更改,以便将依赖传递给它,通过这样做,使用(UIHandler)的代码可以确定使用(ISMSService)的哪个具体实现:

public class UIHandler
{
    private readonly ISMSService _SMSService;

    public UIHandler(ISMSService SMSService)
    {
        _SMSService = SMSService;
    }

    public void SendConfirmationMsg(string mobileNumber)
    {
        _SMSService.SendSMS(mobileNumber, "Your order has been shipped successfully!");
    }
}

现在,与类(UIHandler)对话的UI表单负责传递要使用的接口(ISMSService)的哪个实现。这意味着我们反转了控件,(UIHandler)不再负责决定使用哪个实现,而是由调用代码来决定。我们实现了控制反转原理,DI是其中的一种。

UI表单代码如下所示:

class Program
{
    static void Main(string[] args)
    {
        ISMSService _SMSService = new MockSMSService(); // dependency

        UIHandler _UIHandler = new UIHandler(_SMSService);
        _UIHandler.SendConfirmationMsg("96279544480");

        Console.ReadLine();
    }
}

其他回答

DI和IOC是两种主要侧重于提供组件之间的松耦合的设计模式,或者简单地说,这是一种解耦对象之间传统依赖关系的方法,这样对象之间就不会紧密相连。

通过下面的例子,我试图解释这两个概念。

以前我们是这样写代码的

Public MyClass{
 DependentClass dependentObject
 /*
  At somewhere in our code we need to instantiate 
  the object with new operator  inorder to use it or perform some method.
  */ 
  dependentObject= new DependentClass();
  dependentObject.someMethod();
}

使用Dependency注入,依赖注入器将负责对象的实例化

Public MyClass{
 /* Dependency injector will instantiate object*/
 DependentClass dependentObject

 /*
  At somewhere in our code we perform some method. 
  The process of  instantiation will be handled by the dependency injector
 */ 

  dependentObject.someMethod();
}

上述将控件交给其他容器(例如容器)进行实例化和注入的过程可以称为控制反转,IOC容器为我们注入依赖项的过程可以称为依赖项注入。

IOC是程序控制流颠倒过来的原则:不是由程序员控制程序的流,而是由程序通过减少程序员的开销来控制流程。程序用来注入依赖的过程称为DI

这两个概念一起工作为我们提供了一种编写更加灵活、可重用和封装的代码的方法,这使得它们在设计面向对象的解决方案时成为重要的概念。

也推荐阅读。

什么是依赖注入?

你也可以在这里查看我的一个类似的答案

控制反转和依赖注入的区别

与其直接对比DI和IoC,不如从头开始:每个重要的应用程序都依赖于其他代码段。

所以我写一个类,MyClass,我需要调用一个方法YourService…我需要以某种方式获取YourService的一个实例。最简单、最直接的方法是自己实例化它。

YourService service = new YourServiceImpl();

直接实例化是获取依赖项的传统(过程性)方法。但它有许多缺点,包括MyClass与YourServiceImpl的紧密耦合,这使得我的代码难以更改和测试。MyClass并不关心YourService的实现是什么样子,所以MyClass不想负责实例化它。

我更喜欢把这个责任从MyClass转移到MyClass之外的东西。最简单的方法是将实例化调用(new YourServiceImpl();)移动到其他类中。我可以将这个类命名为Locator,或者Factory,或者其他任何名称;但重点是MyClass不再对YourServiceImpl负责。我颠倒了依赖关系。太好了。

问题是,MyClass仍然负责对定位器/工厂/任何东西的调用。因为我反转依赖关系所做的全部工作就是插入一个中间人,所以现在我耦合到中间人(即使我没有耦合到中间人给我的具体对象)。

我并不真正关心依赖项来自何处,因此我宁愿不负责进行检索依赖项的调用。仅仅反转依赖本身是不够的。我想反转整个过程的控制。

What I need is a totally separate piece of code that MyClass plugs into (call it a framework). Then the only responsibility I'm left with is to declare my dependency on YourService. The framework can take care of figuring out where and when and how to get an instance, and just give MyClass what it needs. And the best part is that MyClass doesn't need to know about the framework. The framework can be in control of this dependency wiring process. Now I've inverted control (on top of inverting dependencies).

将MyClass连接到框架中有不同的方法。注入就是这样一种机制,通过这种机制,我只需声明一个我期望框架提供的字段或参数,通常是在它实例化MyClass时。

我认为所有这些概念之间的关系层次比这个线程中的其他图表所显示的要稍微复杂一些;但其基本思想是,这是一种等级关系。我觉得这和野外的DIP是同步的。

我在Dzone.com上找到了最好的例子,这对理解IOC和DI之间的真正区别非常有帮助

“IoC就是让别人为你创建对象。”因此,与其在代码中写入“new”关键字(例如,MyCode c=new MyCode()),对象是由其他人创建的。这个“其他人”通常被称为IoC容器。这意味着我们将责任(控制)移交给容器以获得对象的实例,这称为控制反转。 意思是你不用new操作符来创建对象,而是让容器来为你做。

   DI(Dependency Injection):  Way of injecting properties to an object is 
   called 
  Dependency injection.
   We have three types of Dependency injection
    1)  Constructor Injection
    2)  Setter/Getter Injection
    3)  Interface Injection
   Spring will support only Constructor Injection and Setter/Getter Injection.

阅读全文IOC和全文DI

IoC概念最初出现在过程式编程时代。因此,从历史背景来看,IoC讨论了控制流所有权的倒置,即谁拥有以所需顺序调用函数的责任——无论是函数本身还是应该将其倒置到某个外部实体。

However once the OOP emerged, people began to talk about IoC in OOP context where applications are concerned with object creation and their relationships as well, apart from the control-flow. Such applications wanted to invert the ownership of object-creation (rather than control-flow) and required a container which is responsible for object creation, object life-cycle & injecting dependencies of the application objects thereby eliminating application objects from creating other concrete object.

从这个意义上讲,DI与IoC不同,因为它不是关于控制流的,但是它是一种Io*,即对象创建的所有权倒置。

我解释DI和IoC的方式有什么问题?

让我们从SOLID的D开始,看看Scott Millett的书《Professional ASP. IoC》中的DI和IoC。NET设计模式":

Dependency Inversion Principle (DIP) The DIP is all about isolating your classes from concrete implementations and having them depend on abstract classes or interfaces. It promotes the mantra of coding to an interface rather than an implementation, which increases flexibility within a system by ensuring you are not tightly coupled to one implementation. Dependency Injection (DI) and Inversion of Control (IoC) Closely linked to the DIP are the DI principle and the IoC principle. DI is the act of supplying a low level or dependent class via a constructor, method, or property. Used in conjunction with DI, these dependent classes can be inverted to interfaces or abstract classes that will lead to loosely coupled systems that are highly testable and easy to change. In IoC, a system’s flow of control is inverted compared to procedural programming. An example of this is an IoC container, whose purpose is to inject services into client code without having the client code specifying the concrete implementation. The control in this instance that is being inverted is the act of the client obtaining the service.

米勒特,C(2010)。专业的ASP。NET设计模式。威利出版社,7-8。