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

时间:2014-12-21 14:56:58

标签: c# design-patterns dependency-injection inversion-of-control

我正在学习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类的构造函数中看到依赖注入。

请理解我的理解。

2 个答案:

答案 0 :(得分:2)

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

这个怎么样?在Dependency Injection - Introduction

快速介绍了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();
}

答案 1 :(得分:1)

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

访问此帖子了解详情Inversion of Control vs Dependency Injection