2014-01-10 89 views
0

我在這裏死去,試圖用我的工作單元實現通用存儲庫。這將與我正在進行的特定項目配合使用。但我無法掌握正確的語法。如果我只能得到下面的工作爲出發點......在運行時創建未知類型的通用存儲庫

我希望能夠做一個

unit_of_work.Repository<don't-know-until-runtime>().Insert(run-time-object); 

,我不會知道,直到在運行什麼樣的對象我將處理,我只知道它將是類型'BaseClass'。

非常感謝您的幫助。下面我試着把代碼燒掉。

public class BaseClass 
{ 
} 

public class SubClass1 : BaseClass 
{ 
    public SubClass1() 
     : base() 
    { 
    } 
} 

public interface IRepository<TEntity> where TEntity : class 
{ 
    void Insert(TEntity entity); 
} 


public class Repository<TEntity> : IRepository<TEntity> where TEntity : class 
{ 
    public void Insert(TEntity entity) 
    { 
     System.Diagnostics.Debug.WriteLine("got here!!"); 
    } 
} 

public class UnitOfWork 
{ 
    public virtual IRepository<TEntity> Repository<TEntity>() where TEntity : class 
    { 
     var type = typeof(TEntity).Name; 
     var repositoryType = typeof(Repository<>); 

     return (IRepository<TEntity>) Activator.CreateInstance(repositoryType.MakeGenericType(typeof(TEntity))); 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     UnitOfWork unit_of_work = new UnitOfWork(); 

     SubClass1 testClass1 = new SubClass1(); 

     // this works fine, when I know the type in advance... 
     unit_of_work.Repository<SubClass1>().Insert(testClass1); 

     // ... but when I don't know the type, then what? 
     // (All I know is that the incoming object will be of type BaseClass) 
    } 
} 
+1

is this C++?你能否用語言標記問題? – Bohemian

+0

@Bohemian我可以和我有,謝謝。 –

+0

我*通常*發現當有人走「我不會知道這裏的類型」時,那麼設計中還有其他的東西是錯的。注我說**通常是**。 –

回答

0

只是聲明你的資料庫和UOW方法與BaseClass的必要約束類型:

public interface IRepository<TEntity> where TEntity : BaseClass 
... 
public class Repository<TEntity> : IRepository<TEntity> where TEntity : BaseClass 
... 
public virtual IRepository<TEntity> Repository<TEntity>() where TEntity : BaseClass 

,然後你可以這樣做:

unit_of_work.Repository<BaseClass>().Insert(<whatever>); 

這工作,因爲通用逆變的。

+0

這很好 - 謝謝。只是一件事:假設我需要一個TEntity FindById(對象id) - 方法在我的資源庫中 - 如果我需要找到一個SubClass1對象,但是隻在運行時才知道這個存儲庫應該如何實例化?例如,如果SubClass1對象來自FindObject(BaseClass objectToFind) - 方法。 –

相關問題