如何使用MEF导入多个插件/部件?

时间:2009-09-18 15:31:00

标签: c# mef

我是MEF的新手,我正在尝试使用它来构建一个插件系统,但是我被困在第一步。

我正在关注article by Andrew Whitechapel。我已经下载了他的示例代码并且运行正常(如果你删除了一个“导出”程序集 - 它们在他的示例中是互斥的 - 并且引用了MEF程序集。)

该示例说明了导入单个零件。我想导入多个部分(全部基于相同的界面)。所以,我按如下方式更改了示例代码:

[Import]
// OLD - public Interface.ICalculate Calculate { get; set; }
public IEnumerable<Interface.ICalculate> Calculators { get; set; }

// OLD - Console.WriteLine(
// OLD -     String.Format("{0}", Calculate.Circumference(4)));
foreach (Interface.ICalculate calculator in Calculators)
{
    Console.WriteLine(
    String.Format("{0}", calculator.Circumference(4)));
}

我还为IEnumerable导入了System.Collections.Generic。

关键变化是第一个。据我了解,这将允许我从多个组件导入零件。但是,我收到以下错误:

No valid exports were found that match the constraint

此时我甚至没有添加多个“插件”程序集。还是只有一个。

为了完整性,这里是他在“插件”类库中的导出定义(我没有碰过):

[Export(typeof(Interface.ICalculate))]
public class Calculate : Interface.ICalculate

有什么想法吗?我在这里挠头。我搜索了SO和MEF论坛,但可以找到任何启​​发我的东西。

我正在使用VS 2008 SP1(未安装2010测试版)和最新的System.ComponentModel.Composition程序集(2009.26.8.0)。

1 个答案:

答案 0 :(得分:5)

MEF预览版第5版改变了这一点。您现在需要使用ImportManyAttribute而不是ImportAttribute:

[ImportMany]
public IEnumerable<Intertface.ICalculate> Calculators { get; set; }

有关详细信息,请参阅announcement for PR5

相关问题