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

既然你已经定义了仓库接口为返回一个特定的类型,为什么你认为这是毫无意义的给你希望它在客户端代码返回类型?

如果你不关心返回类型,那么整个通用接口设计就毫无意义,这只是没有意义。

如果您希望存储库对象只能使用指定的类型,那么您将需要三个对象(或可能是一个具有三个接口的对象,具体取决于实现语言)来提供您的项目存储库,批次存储库和任务存储库。