简体   繁体   English

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

[英]How does one import multiple plugin/parts using MEF?

I'm new to MEF and am trying to use it to build a plug-in system, but am stuck at step one. 我是MEF的新手,正在尝试使用它来构建插件系统,但仅限于第一步。

I'm following an article by Andrew Whitechapel . 我正在关注Andrew Whitechapel文章 I've downloaded his sample code an it runs OK (if you remove one of the "exporting" assemblies - they are mutually exclusive in his sample - and reference the MEF assembly). 我已经下载了他的示例代码,它可以正常运行(如果您删除了一个“导出”程序集-它们在他的示例中是互斥的,并引用了MEF程序集)。

The sample illustrates importing a single part. 该示例说明了导入单个零件。 I want to import multiple parts (all based on the same interface). 我想导入多个零件(全部基于相同的界面)。 So, I change the sample code as follows: 因此,我将示例代码更改如下:

[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)));
}

I also imported System.Collections.Generic for the IEnumerable. 我还为IEnumerable导入了System.Collections.Generic。

The key change is the first one. 关键的变化是第一个。 As I understand it, this will allow me to import parts from multiple assemblies. 据我了解,这将允许我从多个装配体中导入零件。 However, I get the following error: 但是,出现以下错误:

No valid exports were found that match the constraint

At this point I haven't even added multiple "plugin" assemblies. 在这一点上,我什至还没有添加多个“插件”程序集。 Still just have the one. 仍然只有一个。

For completeness here's his export definition (which I haven't touched) in the "plugin" class library: 为了完整起见,这是他在“插件”类库中的导出定义(我没有碰过):

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

Any ideas? 有任何想法吗? I'm scratching my head here. 我在这里挠头。 I've searched SO and the MEF forums, but could find anything to enlighten me. 我已经搜索过SO和MEF论坛,但可以找到启发我的东西。

I'm using VS 2008 SP1 (no 2010 beta installed) and the latest System.ComponentModel.Composition assembly (2009.26.8.0). 我正在使用VS 2008 SP1(未安装2010 Beta)和最新的System.ComponentModel.Composition程序集(2009.26.8.0)。

MEF Preview Release 5 changed this. MEF预览版本5对此进行了更改。 You now need to use ImportManyAttribute instead of ImportAttribute: 现在,您需要使用ImportManyAttribute而不是ImportAttribute:

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

For details, see the announcement for PR5 . 有关详细信息,请参阅PR5公告

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM