2011-02-05 92 views
9

我刚刚开始使用Managed Extensibility框架。我有一个导出的类和一个导入语句:带有ImportMany和ExportMetadata的MEF

[Export(typeof(IMapViewModel))] 
[ExportMetadata("ID",1)] 
public class MapViewModel : ViewModelBase, IMapViewModel 
{ 
} 

    [ImportMany(typeof(IMapViewModel))] 
    private IEnumerable<IMapViewModel> 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获取导出的类。不,我试图改变这种使用懒列表,包括元数据,以便我可以筛选出我需要的类(相同的出口如前)

[ImportMany(typeof(IMapViewModel))] 
    private IEnumerable<Lazy<IMapViewModel,IMapMetaData>> 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<IMapViewModel,IMapMetaData> item in maps) 
     { 
      MapView = (MapViewModel)item.Value; 
     }    
    } 

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

+0

你的元数据接口是什么样的? – 2011-02-05 23:36:56

+0

不知道你可以做一个ImportMany包括元数据。太好了! – juFo 2012-07-17 21:14:44

回答

8

它可能不匹配,因为你的元数据接口不匹配导出的元数据。为了配合还有你的样品出口,元数据接口应该是这样的:

public interface IMapMetaData 
{ 
    int ID { get; } 
} 
0

添加元数据从一个类派生的类到InheritedExport得到了应用,还必须采用同样的InheritedExport属性到派生类。否则,添加到派生类的metdata将被隐藏并且不可用。

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

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