c# - 具有 ImportMany 和 ExportMetadata 的 MEF

标签 c# 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 没有任何元素。我怀疑我在某处犯了一个明显而愚蠢的错误..

最佳答案

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

public interface IMapMetaData
{
    int ID { get; }
}

关于c# - 具有 ImportMany 和 ExportMetadata 的 MEF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4909067/

相关文章:

javascript - 模型未从 View 中获取所有属性值(仅新添加的属性)

c# - MVC4 命名部分 View "_XXPartial"..预期的 Controller 名称是什么?

c# - 使用 MEF 延迟加载 DLL

enterprise-library - MEF、EntLib 和 Prism 之间的区别

c# - 并行化作业的更好方法

c# - youtube api:上传无效

c# - 服务响应异常 : The specified object was not found in the store

.net - 如何在没有导出属性的情况下在 MEF 中导出类型? (例如以编程方式)

prism - 在 Prism 4.0 和 MEF 中将嵌套 View 连接到 View 模型

c# - Visual Studio 2010 MEF 与 MPF?