0

我現在正在圍繞着試圖讓許多IEnumerables使用依賴注入的模式。依賴注入和泛型集合

我有三種類型的對象,我想從我的數據庫返回:項目,批次和任務。我想創建一個具有以下形式的存儲庫:

public interface IRepository<T> 
{ 
    IEnumerable<T> GetAll(); 
    IEnumerable<T> GetAllActive(); 
    IEnumerable<T> GetItemsByUserName(string UserName); 
    T GetItemById(int ID); 
} 

所以,當我創建一個具體的實施ProjectRepository的,它看起來就像這樣:

IEnumerable<Project> GetAll(); 
IEnumerable<Project> GetAllActive(); 
IEnumerable<Project> GetItemsByUserName(string UserName); 
Project GetItemById(int ID); 

也是類似的任務:

IEnumerable<Task> GetAll(); 
IEnumerable<Task> GetAllActive(); 
IEnumerable<Task> GetItemsByUserName(string UserName); 
Task GetItemById(int ID); 

我的困難是試圖在我的調用代碼中聲明一個IRepository。當我宣佈參考時,我發現自己需要聲明一個類型:

private IRepository<Project> Repository; 

......這當然是毫無意義的。我在某個地方出了問題,但目前無法擺脫困境。我如何使用依賴注入,以便我可以聲明一個使用所有三種具體類型的接口?

希望我已經正確地解釋了我自己。

回答

5

使用泛型:

public class YourClass<T> 
{ 
    public YourClass(IRepository<T> repository) 
    { 
     var all = repository.GetAll(); 
    } 
} 

當然,在某些時候,你需要提供T,這可能是這樣的:

var projectClass = yourDIContainer.Resolve<YourClass<Project>>; 

與您的DI容器註冊您的類型看,如果您的DI容器支持開放式泛型,這可能會很有用。例如,請查看this post,其中顯示Unity如何支持此操作。

0

希望這可以幫助你在你想要的代碼的方式。

public class Repository : IRepository<Repository> 
{ 

    public Repository() 
    { 
    } 

    #region IRepository<Repository> Members 

    public IEnumerable<Repository> GetAll() 
    { 
     throw new Exception("The method or operation is not implemented."); 
    } 

    public IEnumerable<Repository> GetAllActive() 
    { 
     throw new Exception("The method or operation is not implemented."); 
    } 

    public IEnumerable<Repository> GetItemsByUserName(string UserName) 
    { 
     throw new Exception("The method or operation is not implemented."); 
    } 

    public Repository GetItemById(int ID) 
    { 
     throw new Exception("The method or operation is not implemented."); 
    } 

    #endregion 
} 



public class RepositoryCreator<T> where T : IRepository<T> 
{ 
    public IRepository<Repository> getRepository() 
    { 
     Repository r = new Repository(); 
     return r; 
    } 


    public IRepository<Blah> getBlah() 
    { 
     Blah r = new Blah(); 
     return r; 
    } 
} 
0

既然你已經定義了倉庫接口爲返回一個特定的類型,爲什麼你認爲這是毫無意義的給你希望它在客戶端代碼返回類型?

如果你不關心返回類型,那麼整個通用接口設計就毫無意義,這只是沒有意義。

如果您希望存儲庫對象只能使用指定的類型,那麼您將需要三個對象(或可能是一個具有三個接口的對象,具體取決於實現語言)來提供您的項目存儲庫,批次存儲庫和任務存儲庫。