繁体   English   中英

理解控制和依赖注入的反转

[英]Understanding Inversion of Control and Dependency Injection

我正在学习IoC和DI的概念。 我查了几个博客,下面是我的理解:

不使用IoC的紧耦合示例:

Public Class A
{
     public A(int value1, int value2)
     {
    return Sum(value1, value2);
     }

     private int Sum(int a, int b)
     {
    return a+b;
     }
}     

IoC之后:

Public Interface IOperation
{
    int Sum(int a, int b);
}

Public Class A
{ 
     private IOperation operation;

     public A(IOperation operation)
     {
    this.operation = operation;
     }

     public void PerformOperation(B b)
     {
    operation.Sum(b);
     }
}

Public Class B: IOperation
{
   public int Sum(int a, int b)
   {
       return a+b;
   }
}

A类中的PerformOperation方法是错误的。 我猜,它再次紧密耦合,因为参数被硬编码为B b。

在上面的例子中,IoC在哪里,因为我只能看到A类构造函数中的依赖注入。

请理解我的理解。

您的“After IoC”示例实际上是“After DI”之后。 您确实在A类中使用DI。但是,您似乎在DI之上实现了一个适配器模式,这实际上是不必要的。 更不用说,当接口需要2个参数时,你只使用A类中的一个参数调用.Sum。

这个怎么样? 依赖注入 - 介绍中快速介绍DI

public interface IOperation
{
  int Sum(int a, int b);
}

private interface IInventoryQuery
{
  int GetInventoryCount();
}

// Dependency #1
public class DefaultOperation : IOperation
{
  public int Sum(int a, int b)
  {
    return (a + b);
  }
}

// Dependency #2
private class DefaultInventoryQuery : IInventoryQuery
{
  public int GetInventoryCount()
  {
    return 1;
  }
}


// Dependent class
public class ReceivingCalculator
{
  private readonly IOperation _operation;
  private readonly IInventoryQuery _inventoryQuery;

  public ReceivingCalculator(IOperation operation, IInventoryQuery inventoryQuery)
  {
    if (operation == null) throw new ArgumentNullException("operation");
    if (inventoryQuery == null) throw new ArgumentNullException("inventoryQuery");
    _operation = operation;
    _inventoryQuery = inventoryQuery;
  }

  public int UpdateInventoryOnHand(int receivedCount)
  {
    var onHand = _inventoryQuery.GetInventoryCount();
    var returnValue = _operation.Sum(onHand, receivedCount);

    return returnValue;
  }
}

// Application
static void Main()
{
  var operation = new DefaultOperation();
  var inventoryQuery = new DefaultInventoryQuery();
  var calculator = new ReceivingCalculator(operation, inventoryQuery);

  var receivedCount = 8;
  var newOnHandCount = calculator.UpdateInventoryOnHand(receivedCount);

  Console.WriteLine(receivedCount.ToString());
  Console.ReadLine();
}

简单来说,IOC是一个概念,DI是它的一个实现。

请访问此帖子了解更多详细信息, 控制反转与依赖注入

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM