我正在使用 MEF 构建一个简单的应用程序以更好地理解它,但我遇到了一个问题。该应用程序是一个简单的计算器,您可以创建新的操作。每个操作都是一个导出 IOperation 的类。这是 ADD 操作类:
[Export(typeof(IOperation))]
internal class Add : IOperation
{
CompositionContainer _container;
public string Name
{
get { return "Add"; }
}
public string Symbol
{
get { return "+"; }
}
public IOperand Compute(params IOperand[] operands)
{
IOperand result = _container.GetExportedValue<IOperand>();
result.Value = operands.Sum(e => e.Value);
return result;
}
}
(IOperand 是一个只暴露一个 double 的接口。原因是在版本 2 中你可以有一个像 "(2+2)*4" 这样的表达式)
如您所见,我的问题_container
是当我点击Compute
. 当容器组成一个[ImportMany(typeof(IOperation))]
. 所以我的问题是:有没有办法告诉正在反转控制的容器将自己的引用传递给这个对象?
PS:我不想做_container
公共财产。
Edit1:这是迄今为止 IOperand 的唯一实现:
[Export(typeof(IOperand))]
public class SimpleResult : IOperand
{
private double _value;
public double Value
{
get
{
return _value;
}
set
{
_value = value;
}
}
}
这是“主要”,组合发生的地方:
public class Calculator
{
[ImportMany(typeof(IOperation))]
private List<IOperation> _knownOperations;
private List<ICalculatorButton> _buttons;
private CompositionContainer _container;
public Calculator()
{
_container = new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
_container.SatisfyImportsOnce(this);
_buttons = new List<ICalculatorButton>();
ICalculatorButton button;
for (int i = 0; i < 10; i++)
{
button = _container.GetExportedValue<IDigitButton>();
button.Symbol = i.ToString();
((IDigitButton)button).Value = i;
_buttons.Add(button);
}
foreach (IOperation op in _knownOperations)
{
button = _container.GetExportedValue<IOperationButton>();
button.Symbol = op.Symbol;
((IOperationButton)button).Operation = op;
_buttons.Add(button);
}
}
public IReadOnlyList<IOperation> KnownOperations
{
get { return _knownOperations.AsReadOnly(); }
}
public IReadOnlyList<ICalculatorButton> Buttons
{
get { return _buttons.AsReadOnly(); }
}
public IOperand Calculate(IOperation operation, params IOperand[] operands)
{
IOperand result = operation.Compute(operands);
return result;
}
public IOperand Calculate(IOperation operation, params double[] operands)
{
List<IOperand> res = new List<IOperand>();
foreach (double item in operands)
{
IOperand aux = _container.GetExportedValue<IOperand>();
aux.Value = item;
res.Add(aux);
}
return Calculate(operation, res.ToArray());
}
}