2010-07-20 64 views
3

我已經編寫了一個服務這樣的:現在如何使用MEF導入多個實例?

public interface IMyInterface 
{ 
    ... 
} 

[Export(typeof(IMyInterface))] 
internal class MyService : IMyInterface 
{ 
    ... 
} 

,我想導入的MyService MEF的幾種情況在我的主程序。

我該怎麼做?

隨着[Import] private IMyInterface MyService { get; set; }我只能得到MyService 1個實例。 在我的主要程序,我想MEF組成前動態指定的MyService進口實例的數量。

我不想使用[ImportMany],因爲我不想在我的MyService實現中指定導出的數量。

你能幫我嗎?

回答

6

你可能不希望這樣做,因爲直的進口,但得到的容器幾次出口值。正因爲如此,您需要更改創建策略,以非共享,這迫使容器每次實例化一個新的實例。

[Export(typeof(IMyInterface)) PartCreationPolicy(CreationPolicy.NonShared)] 
internal class MyService : IMyInterface 
{ 
    ... 
} 

然後從容器中獲得的價值:

List<IMyInterface> instances = new List<IMyInterface>(); 
for (int i = 0; i < 10; i++) { 
    instances.Add(container.GetExportedValue<IMyInterface>()); 
} 
+0

謝謝你,這是我需要什麼;-)。 – 2010-07-20 12:11:24

+1

@Patrice它通常會更好地使用ExportFactory 而不是調用到容器多次。看到這個答案:http://stackoverflow.com/questions/3285469/loading-plugins-at-runtime-with-mef/3286167#3286167 – 2010-07-20 18:26:57