2012-01-13 78 views
2

我正在使用結構圖自動將DataContext注入到我的Repository構造函數中。我給了一個名字(例如「Project1」),我需要爲項目動態創建一個Repository實例。使用反射和結構圖

我使用標準的命名約定,所以我知道它是「Project1DataContext」。我設法使用反射來創建我的Project1DataContext的一個實例,但它是一個對象類型。問題是我需要將一個Project1DataContext對象傳遞到我的Repository中以創建它的一個實例。我如何使用反射來做到這一點?是否有可能通過某種方式投射物體?

Assembly myDataContextAssembly = typeof(SomeTypeInTheAssembly).Assembly; 
Type dataContextType = myDataContextAssembly.GetType(ProjectName + "DataContext"); 
object dataContext = Activator.CreateInstance(dataContextType);  
// I need to cast the data context here 
IRepository<Project1DataContext> = new Repository<Project1DataContext>(dataContext) 

在平均時間,我將使用if語句,但這不是一個可行的解決方案,如果我有100多個項目。我需要使用反射和理想情況下有結構圖確定類型併爲我注入它們。

+0

你能舉出一個或兩個if語句嗎?這會讓你更容易看到你想要解決的問題。 – Clafou 2012-01-16 22:54:09

回答

1

根據我所瞭解的信息,您希望在將該類型傳遞給IRepository和Repository泛型類之前,將dataContext對象轉換爲其真實類型。這意味着你想讓他們混凝土。你可以使它們在運行時具體,但而不是通過傳遞一個Type對象作爲一個通用的參數。另外,這裏不能依賴泛型類型推斷,因爲這只是在編譯時完成的。

我會假設你的方法返回一個IRepository或Respository(沒有泛型參數)。

以下是您需要做的:使用dataContextType爲存儲庫<>創建一個具體類型,然後使用該具體類型創建一個Repository對象,然後將其轉換爲Repository並返回它。

 Assembly myDataContextAssembly = typeof(SomeTypeInTheAssembly).Assembly; 
     Type dataContextType = myDataContextAssembly.GetType(ProjectName + "DataContext"); 
     Type concreteRepositoryType = typeof(Generic<>).MakeGenericType(dataContextType); 
     Repository repository = (Repository)System.Activator.CreateInstance(concreteRepositoryType); 
     return repository;