2014-01-23 66 views
0

我構建的數據庫導入應用程序比我想要的可擴展(可根據需要添加自定義數據庫模型)。我的基本組件具有擴展類型必須實現的方法:MapData & SaveData。在抽象基類中使用MEF

我將基地定義爲一個抽象類,當擴展類型在同一個名稱空間中時,所有東西都可以工作。但是,我想在運行時使用MEF在不同的名稱空間中導入擴展類型,但我無法弄清楚如何執行此操作。

基類:

namespace Program 
{ 
    public abstract class Component 
    { 
     public abstract string TypeName { get; } 
     public abstract DataSet MapData(DataSet db); 
     public abstract bool SaveData(); 
    } 
} 

擴展類(在一個單獨的項目):

using Program.Component; 
namespace ExtendedType 
{ 
    [Export(typeof(Component)] 
    class Type1 : Component 
    { 
     public override string TypeName { get { return "Type1" } } 
     public override DataSet MapData(DataSet db) 
     { 
      // create various object models from db here 
      return db; 
     } 
     public override bool SaveData() 
     { 
      // save object models 
      return true; 
     } 
    } 
} 

計劃導入所有擴展類型:

namespace Program 
{ 
    [ImportMany(typeof(Component))] 
    public IEnumerable<Component> componentTypes; 

    public Program() 
    { 
     var catalog = new AggregateCatalog(); 
     catalog.Catalogs.Add(new AssemblyCatalog(typeof(Component).Assembly)); 
     container = new CompositionContainer(catalog); 
     this.container.ComposeParts(this); 
    } 
} 

據我所閱讀時,IEnumerable上的[ImportMany]屬性應該在運行時填充,但它總是空的。 CompositionContainer也是空的。

我的設置不正確?我如何獲得擴展組件類型的列表?

+0

鏈接類似於什麼我想做的事: 擴展類型在同一個名字:[鏈接](http://vivekcek.wordpress.com/2012/10/ 12/abstract-class-with-mef /) 導出/導入不同命名空間中的很多類型:[link](http://www.codeproject.com/Articles/188054/An-Introduction-to-Managed-Extensibility-Framework ) – David

回答

0

我結束了對MEF組件創建一個Extensions目錄住在和設置在App.Config中的變量,以及其他項目的構建目錄指向那裏。感謝@JaredPar的幫助。我發現

var extensionFolder = ConfigurationManager.AppSettings["ExtensionPath"]; 
var solutionPath = Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.FullName; 
var catalog = new AggregateCatalog(); 
catalog.Catalogs.Add(new DirectoryCatalog(solutionPath + extensionFolder)); 
var container = new CompositionContainer(catalog); 
container.ComposeParts(this); 
2

MEF只會搜索由CompositionContainer定義的一組類型/程序集。在這種情況下,Type1的程序集不在其中,因此它從未找到。爲了這個或者這個工作,你還需要在CompositionContainer中包含程序集Type1

catalog.Catalogs.Add(new AssemblyCatalog(typeof(Type1).Assembly) 
+0

我可能錯了,但是每次添加新類型時都不必編輯程序?我可以使用一個目錄,但我不知道如何強制類型在不同的項目中編譯到某個目錄: catalog.Catalogs.Add(new DirectoryCatalog(Path.GetDirectoryName(Assembly.GetExecutingAssembly()。Location))) ; – David

+1

@Clarke大多數MEF基本系統將只添加給定目錄中的所有程序集,以便它可配置 – JaredPar

+0

@Clarke在我的項目中,我爲每個將二進制文件複製到「模塊」目錄的模塊項目構建了一個後期構建步驟。 'xcopy'是國王! – Gusdor