2010-06-10 138 views
0

如果這個問題已經被問了100次,我很抱歉,但是我真的很努力地讓它工作。用MEF導入導出對象

假設我有三個項目。

  • Core.dll
    • 具有公共接口
  • Shell.exe
    • 載荷在裝配夾中的所有模塊。
    • 參考Core.dll
  • ModuleA.dll
    • 出口名稱,模塊的版本。
    • 參考Core.dll

Shell.exe有一個[出口]包含我需要注入到所有加載的模塊第三方應用程序的單一實例。

到目前爲止,我在Shell.exe代碼:

static void Main(string[] args) 
{ 
     ThirdPartyApp map = new ThirdPartyApp(); 

     var ad = new AssemblyCatalog(Assembly.GetExecutingAssembly()); 
     var dircatalog = new DirectoryCatalog("."); 
     var a = new AggregateCatalog(dircatalog, ad); 

     // Not to sure what to do here. 
} 

class Test 
{ 
    [Export(typeof(ThirdPartyApp))] 
    public ThirdPartyApp Instance { get; set; } 

    [Import(typeof(IModule))] 
    public IModule Module { get; set; } 
} 

我需要從Main方法來創建測試的情況下,和負載Instancemap然後加載從ModuleA.dll模塊即在執行目錄中,然後將[Import] Instance放入加載的模塊中。

ModuleA我有這樣一個類:

[Export(IModule)] 
class Module : IModule 
{ 
    [Import(ThirdPartyApp)] 
    public ThirdPartyApp Instance {get;set;} 
} 

我知道我有一半的辦法,我只是不知道如何把它放在一起,這主要與裝載了測試用的實例mapMain

任何人都可以幫助我。

回答

0

我似乎能夠得到它的工作這種方式,在測試類的構造函數(是的,我不知道在構造函數中做的工作,我將其移出):

public Test() 
    { 
     ThirdPartyApp map = new ThirdPartyApp(); 
     this.MapInfoInstance = map; 

     //What directory to look for! 
     String strPath = AssemblyDirectory; 
     using (var Catalog = new AggregateCatalog()) 
     { 
      DirectoryCatalog directorywatcher = new DirectoryCatalog(strPath, "*.dll"); 
      Catalog.Catalogs.Add(directorywatcher); 
      CompositionBatch batch = new CompositionBatch(); 
      batch.AddPart(this); 
      CompositionContainer container = new CompositionContainer(Catalog); 
      //get all the exports and load them into the appropriate list tagged with the importmany 
      container.Compose(batch); 

      foreach (var part in Catalog.Parts) 
      { 
       container.SatisfyImportsOnce(part); 
      } 
     } 

     Module.Run(); 
    } 
0

你的主要方法或許應該是這樣的:

static void Main(string[] args) 
{ 
    var exeCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); 
    var dircatalog = new DirectoryCatalog("."); 
    var aggregateCatalog = new AggregateCatalog(exeCatalog, dirCatalog); 
    var container = new CompositionContainer(aggregateCatalog); 
    var program = container.GetExportedValue<Program>(); 

    program.Run(); 
} 

爲了使可作爲可通過您的模塊引入的一部分ThirdPartyApp類的實例,你有兩個選擇。首先是明確這種情況下與ComposeExportedValue擴展方法是這樣添加到容器:

container.ComposeExportedValue<ThirdPartyApp>(new ThirdPartyApp()); 

或者,您也可以通過具有像這樣的一類通過屬性導出:

public class ThirdPartyAppExporter 
{ 
    private readonly ThirdPartyApp thirdPartyApp = new ThirdPartyApp(); 

    [Export] 
    public ThirdPartyApp ThirdPartyApp { get { return thirdPartyApp; } } 
}