带有ImportMany和ExportMetadata的MEF

Fur*_*nes 11 c# mef

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

[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;                
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

[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;
        }            
    }
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*ted 8

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

public interface IMapMetaData
{
    int ID { get; }
}
Run Code Online (Sandbox Code Playgroud)