【发布时间】:2014-12-21 14:56:57
【问题描述】:
我正在学习 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 在哪里,因为我只能看到 Class A 的构造函数中的依赖注入。
请澄清我的理解。
【问题讨论】:
标签: c# design-patterns dependency-injection inversion-of-control