相关疑难解决方法(0)

存储库模式与泛型和DI

我有一个基本存储库合同,其他合同扩展,如下所示

public interface IBaseRepository<T> where T : class 
{
  IList<T> GetContents();
}
Run Code Online (Sandbox Code Playgroud)

然后还有其他合同,如下所示扩展它

public interface IRepository1 : IBaseRepository<MyClass1>
{
}

public interface IRepository2 : IBaseRepository<MyClass2>
{
}
Run Code Online (Sandbox Code Playgroud)

我按如下方式实现IRepository1

public class Repository1 : IRepository1
{
 public IList<MyClass1> GetContents()
 {
  //some code goes here
 }
} 
Run Code Online (Sandbox Code Playgroud)

同样适用于IRepository2

public class Repository2 : IRepository2
{
 public IList<MyClass2> GetContents()
 {
  //some code goes here
 }
} 
Run Code Online (Sandbox Code Playgroud)

现在我有一个服务Service1,其中包括如下的IService

public class Service1 : IService
{


}
Run Code Online (Sandbox Code Playgroud)

我想在我的服务构造函数中使用我的基本存储库(IBaseRepository),获取此基本存储库的实例并像这样使用它

 public class Service1 : IService
 {
   private IBaseRepository<T> _baseRepository;
   public …
Run Code Online (Sandbox Code Playgroud)

c# generics dependency-injection repository-pattern

1
推荐指数
1
解决办法
2182
查看次数