4

是否可以将接口标记为导出,以便所有派生类都可用于导入?

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

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

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

只要我不标记每一堂课,[Export]它似乎对我不起作用。

4

3 回答 3

4

在当前预览中,您可以尝试在界面上放置一个 [PartExportsInherited] 属性(与 Export 属性一起)。不过,我不确定这是否适用于接口。

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

于 2009-06-16T13:45:18.683 回答
3

是的,在 codeplex 的当前预览中,您可以使用 PartExportsInherited 和 Export 标记接口,以自动导出所有实现者。在即将发布的预览版中,我们可能会对其进行简化,以简单地放置一个属性,可能类似于 [InheritedExport]。

编辑:使用 MEF 预览版 6,现在可以通过在界面上放置 InheritedExport 属性来完成。

于 2009-06-20T02:31:44.760 回答
2

更新:使用 MEF v4。

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

正如预期的那样,从 IMyInterface 继承的任何东西都将作为一个导出。

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

[ImportingConstructor]
public void MyClass([ImportMany] IEnumerable<IMyInterface> myDerivedObjects)
于 2014-01-23T09:46:47.153 回答