繁体   English   中英

带有ImportMany和ExportMetadata的MEF

[英]MEF with ImportMany and ExportMetadata

我刚刚开始使用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;                
        }
    }

这很好用。 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;
        }            
    }

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

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

public interface IMapMetaData
{
    int ID { get; }
}

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM