2011-02-05 21 views
9

Managed Extensibilityフレームワークを使い始めたばかりです。私はエクスポートされたクラスとインポートステートメントを持っています:ImportManyとExportMetadataを使用した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は、エクスポートされたクラスを取得します。ノー私は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; 
     }    
    } 

私は(以前と同じ輸出を)必要とするクラスを除外することができるように怠惰なリストを使用してメタデータを含めるために、これを変更してみてください。

+0

メタデータインターフェイスはどのように見えますか? –

+0

メタデータを含むImportManyを実行できるかどうかはわかりませんでした。いいよ! – juFo

答えて

8

メタデータインターフェイスがエクスポートのメタデータと一致しないため、おそらく一致しない可能性があります。あなたが示されてきたサンプルのエクスポートを一致させるには、メタデータ・インタフェースは、次のようになります。

public interface IMapMetaData 
{ 
    int ID { get; } 
} 
+0

私はそれが何かばかげたことを知っていた、それを見ることができなかった。私のインターフェースでは、IDは文字列でした... – Furnes

0

InheritedExportが適用されたクラスから派生したクラスにメタデータを追加するには、あなたも同じInheritedExport属性を適用する必要があります派生クラスに追加します。そうしないと、派生クラスに追加されたメタデータは非表示になり、使用できなくなります。

つまり、適用されたメタデータにアクセスするためにLazy<T,TMetadata>を使用していて、インポートが行われていない場合は、InheritedExportをすべての派生クラスに適用しなかった可能性があります。

InheritedExportの代わりにExportを適用すると、パートの別のインスタンスになります。

関連する問題