簡體   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