Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MEF with ImportMany and ExportMetadata

Tags:

c#

mef

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..

like image 206
Furnes Avatar asked Feb 05 '11 19:02

Furnes


1 Answers

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; }
}
like image 85
Daniel Plaisted Avatar answered Sep 17 '22 19:09

Daniel Plaisted