MEF with ImportMany and ExportMetadata
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 incl开发者_StackOverflow中文版ude 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..
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; }
}
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.
精彩评论