Understanding Inversion of Control and Dependency Injection
我正在学习国际奥委会和DI的概念。我查了一些博客,下面是我的理解:
不使用IOC的紧耦合示例:
1 2 3 4 5 6 7 8 9 10 11 12 | Public Class A { public A(int value1, int value2) { return Sum(value1, value2); } private int Sum(int a, int b) { return a+b; } } |
国际奥委会之后:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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。
在上面的示例中,IOC在哪里,因为我只能在类A的构造函数中看到依赖注入。
请澄清我的理解。
你的"在国际奥委会之后"的例子真的是"在DI之后"。您确实在类A中使用了DI。但是,您似乎在DI之上实现了一个适配器模式,这实际上是不必要的。更不用说,当接口需要2个参数时,您只使用类A中的一个参数来调用.sum。
这个怎么样?在依赖注入中有一个对DI的快速介绍-介绍
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | 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是它的一个实现。
访问本文了解更多详细信息,控制反转与依赖注入