带有ImportMany和ExportMetadata的MEF

我刚刚开始使用Managed Extensibility框架。 我有一个导出的类和一个import语句:

[Export(typeof(IMapViewModel))] [ExportMetadata("ID",1)] public class MapViewModel : ViewModelBase, IMapViewModel { } [ImportMany(typeof(IMapViewModel))] private IEnumerable maps; private void InitMapView() { var catalog = new AggregateCatalog(); catalog.Catalogs.Add(new AssemblyCatalog(typeof(ZoneDetailsViewModel).Assembly)); CompositionContainer container = new CompositionContainer(catalog); container.ComposeParts(this); foreach (IMapViewModel item in maps) { MapView = (MapViewModel)item; } } 

这很好用。 IEnumerable获取导出的类。 不,我尝试更改此项以使用Lazy列表并包含元数据,以便我可以过滤掉我需要的类(与以前相同的导出)

 [ImportMany(typeof(IMapViewModel))] private IEnumerable<Lazy> maps; private void InitMapView() { var catalog = new AggregateCatalog(); catalog.Catalogs.Add(new AssemblyCatalog(typeof(ZoneDetailsViewModel).Assembly)); CompositionContainer container = new CompositionContainer(catalog); container.ComposeParts(this); foreach (Lazy item in maps) { MapView = (MapViewModel)item.Value; } } 

在此之后,Ienumerable没有元素。 我怀疑我在某个地方犯了一个明显而愚蠢的错误。

它可能不匹配,因为您的元数据接口与导出上的元数据不匹配。 要匹配您显示的示例导出,您的元数据界面应如下所示:

 public interface IMapMetaData { int ID { get; } } 

要将元数据添加到从已应用InheritedExport的类派生的类中,必须将相同的InheritedExport属性也应用于派生类。 否则,添加到派生类的metdata将被隐藏且不可用。

换句话说,如果您使用Lazy来访问应用的元数据,并且未填充导入,则可能意味着您没有将InheritedExport应用于所有派生类。

如果您改为使用Export而不是InheritedExport ,则最终会得到另一个零件实例。