//契约 Contract
public interface ICalculator
{
int Add(int a, int b);
int Sub(int a, int b);
}
//此处我们导出了契约,这就是一个部件(Part)
[Export(typeof(ICalculator))]
public class DigitalCalculator : ICalculator
{
public int Add(int a, int b)
{
return a + b;
}
public int Sub(int a, int b)
{
return a - b;
}
}
[TestClass]
public class DigitalCalculatorTest
{
private CompositionContainer container;
[Import(typeof(ICalculator))]
public ICalculator calculator;
public DigitalCalculatorTest()
{
//AssemblyCatalog 目录的一种,表示在相应的程序集中搜索
AssemblyCatalog catalog = new AssemblyCatalog(typeof(DigitalCalculator).Assembly);
container = new CompositionContainer(catalog);
//组装部件,ComposeParts是扩展方法
container.ComposeParts(this);
}
[TestMethod]
public void Add_ReturnSum()
{
int x = 3, y = 2;
int actual = calculator.Add(x, y);
int expected = 5;
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Sub_ReturnDiff()
{
int x = 3, y = 2;
int actual = calculator.Sub(x, y);
int expected = 1;
Assert.AreEqual(expected, actual);
}
}