我正在使用MEF構建一個簡單的應用程序,以便更好地理解它,而且我正面臨一個問題。該應用程序是一個簡單的計算器,您可以創建新的操作。每個操作都是導出IOperation的類。這裏的ADD操作類:MEF注入容器
[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是隻公開一個雙A接口的原因,那就是在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());
}
}
哪裏'IOperand'實現出口?你應該可以使用'[Import]'屬性導入它,並且根本不需要引用容器,假設其他地方正在進行組合。 – Matt
@Matt我編輯了這個問題並插入了IOperand的實現。問題是我不認爲我想要「導入」它...我想每次都提供一個新實例計算被調用 – Leonardo