MEF with ImportMany and ExportMetadata

a 夏天 提交于 2020-01-13 07:55:30

问题


I've just started playing around with Managed Extensibility framework. I've got a class that's exported and a import statement:

[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;                
        }
    }

This works just fine. The IEnumerable get the exported classes. No I try to change this to use the Lazy list and include the metadata so that I can filter out the class that i need (same export as before)

[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;
        }            
    }

After this the Ienumerable has no elements. I suspect that i've made an obvious and stupid mistake somewhere..


回答1:


It is probably not matching because your metadata interface doesn't match the metadata on the export. To match the sample export you've shown, your metadata interface should look like this:

public interface IMapMetaData
{
    int ID { get; }
}



回答2:


To add metadata to a class derived from a class to which InheritedExport has been applied, you must apply the same InheritedExport attribute also to the derived class. Otherwise, metdata added to the derived class will be hidden and unavailable.

In other words, if you are using Lazy<T,TMetadata> to access applied metadata, and your imports are not being populated, it may mean you did not apply InheritedExport to all your derived classes.

If you instead apply Export instead of InheritedExport, you will end up with another instance of your part.



来源:https://stackoverflow.com/questions/4909067/mef-with-importmany-and-exportmetadata

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!