2011-06-20 16 views
1

我想動態地(使用反射)將類型添加到MEF目錄,並在運行時定義導出合同。問題是MEF將簡單地使用該類型的完全限定名稱作爲合同,並且我需要將出口合同指定爲特定的接口類型。使用運行時定義的合約動態註冊MEF導出

下面是我用得到我需要添加到MEF目錄類型代碼:

private void RegisterSupportedRepositories(Func<ObjectContext> contextProvider) 
    { 
     var context = contextProvider(); 
     var properties = context.GetType().GetProperties(); 
     var entitySets = properties.Where(property => property.PropertyType.Name == typeof(ObjectSet<>).Name); 

     foreach (var entitySet in entitySets) 
     { 
      var entityType = entitySet.PropertyType.GetGenericArguments()[0]; 
      var repositoryType = typeof(EFRepository<>).MakeGenericType(entityType); 
      ComponentServices.RegisterComponent(repositoryType);     
     } 
    } 

ComponentServices.RegisterComponent定義如下,它得到的AggregateCatalog(從那裏是不相關),然後將TypeCatalogs到總目錄:

public static void RegisterComponent(Type componentType) 
    { 
     var catalog = RetrieveCatalog(); 

     catalog.Catalogs.Add(new TypeCatalog(componentType)); 
    } 

我需要能夠指定添加類型的合同作爲一個接口,這將通常有看起來像這樣的輸出屬性來完成:

[Export(typeof(IRepository<Customer>))] 

的問題是如何動態地添加這個出口合同,從而使出口相當於什麼上面,而不是顯示默認的「EFRepository」合同是MEF從類型本身推斷。

回答

1

如果您可以使用MEF的CodePlex預覽版本,我建議使用新的RegistrationBuilder來執行此操作。以下是描述它的博客文章:MEF's Convention Model

如果您不能使用預覽版本,則可以使用ReflectionModelServices中的方法創建您自己的零件定義,並創建使用它們的目錄實現。

+0

Daniel,感謝您指引我走向正確的道路,我已經構建了自己的使用ReflectionModelServices和AttributedModelServices的類型目錄;現在我可以動態地將非屬性類型添加到MEF。 – Xacron