MEF:标记出口界面

时间:2009-06-16 09:22:03

标签: .net mef

是否可以标记要导出的接口,以便所有派生类都可以导入?

[Export( typeof( IMyInterface ) )]
public interface IMyInterface { ... }

[Import( typeof( IMyInterface ) )]
private readonly ICollection<IMyInterface> m_Concretes = new Collection<IPlugin>();

我不知道在这个例子中哪些类正在实现IMyInterface。这些类本身对MEF一无所知 - 并且不使用[Export]属性。

只要我没有用[Export]标记每个班级,它似乎对我不起作用。

3 个答案:

答案 0 :(得分:4)

在当前预览中,您可以尝试在界面上放置[PartExportsInherited]属性(以及“导出”属性)。不过,我不确定这是否适用于接口。

我们计划增加对在接口上放置导出的支持。

答案 1 :(得分:3)

是的,在codeplex的当前预览中,您可以使用PartExportsInherited和Export标记界面,以便自动导出所有实施者。在上传预览版本中,我们可能会简化这一过程,只需放置一个属性,可能类似于[InheritedExport]。

编辑:使用MEF预览6,现在可以通过在接口上放置InheritedExport属性来完成此操作。

答案 2 :(得分:2)

更新:使用MEF v4。

[InheritedExport(typeof(IMyInterface))]
public interface IMyInterface
{
}

正如所料,从IMyInterface继承的任何内容都将导出为一个。

使用[ImportMany]将它们全部注入:

[ImportingConstructor]
public void MyClass([ImportMany] IEnumerable<IMyInterface> myDerivedObjects)