2012-04-19 8 views
1

私はプラグインシステムにMEF(C#4.0)を使用しています。時には、(主にXMLの逆シリアル化のために)すべてのプラグインの派生型のリストを取得する必要があります。プラグインをインスタンス化せずにこれを行うことはできますか?MEFプラグインクラスのタイプを特定する方法は?

これは動作しますが、インスタンス化が必要になります。

var cat = new DirectoryCatalog(path, "*.dll"); 
var container = new CompositionContainer(cat); 
container.ComposeParts(this); 
foreach (var plugin in Plugins) 
{ 
    // Would be better if this could be done via Metadata! 
    DoStuff(plugin.Value.GetType()); 
} 
// ... 
[ImportMany] 
public Lazy<PluginBase, IPluginMetadata>[] Plugins 
{ 
    get; 
    private set; 
} 

Q:が、それはいくつかのExportAttribute、またはいくつかの他の技術によって、これを達成することは可能ですか?

ありがとうございました。

答えて

2

MEFはこの情報を単独で提供することはできません。 、プロパティを経由して、次の輸出を検討する理由を理解するために:しかし

[Export(typeof(PluginBase))] 
public PluginBase MyPlugin 
{ 
    get 
    { 
     if (someCondition) 
     { 
      return new FooPlugin(); 
     } 
     else 
     { 
      return new BarPlugin(); 
     } 
    } 
} 

、あなたはまだ輸出のメタデータでタイプを含めることができます(下記またはメタデータを含むカスタムエクスポート属性を介して):

[Export(typeof(PluginBase))] 
[ExportMetadata("Type", typeof(Foo))] 
public class Foo : PluginBase 
{ 
} 

とし、IPluginMetadata.Typeメンバーを追加します。

+0

[OK]をクリックします。ただし、この場合、これを各派生クラスに追加する必要があります。 – l33t

+0

@NOPslider:はい。 –

+0

それはあまりにも悪いです:Pしかし、私はそれがなぜそう理解します。ありがとう。 – l33t

0

あなたはまた、ComposablePartsを少し超える反復処理を行いますが、カタログが含まれている静的MEFHelperクラスがあるとすることができ、あなたは私がthis blog postでこれを説明し

public static IEnumerable<Type> GetExportedTypes<T>() 
{ 
    return catalog.Parts 
     .Select(part => ComposablePartExportType<T>(part)) 
     .Where(t => t != null); 
} 

private static Type ComposablePartExportType<T>(ComposablePartDefinition part) 
{ 

    if (part.ExportDefinitions.Any(
     def => def.Metadata.ContainsKey("ExportTypeIdentity") && 
      def.Metadata["ExportTypeIdentity"].Equals(typeof(T).FullName))) 
    { 
     return ReflectionModelServices.GetPartType(part).Value; 
    } 
    return null; 
} 

このコードを書くことができます(ワーキングサンプルますがありますダウンロードが可能)

関連する問題