【发布时间】:2019-11-12 19:13:56
【问题描述】:
我正在创建一个通用存储库,但对于某些实体,我还需要通用存储库未提供的功能。我有一个接口 IGenericRepository 和具体实现作为具有基本 CRUD 操作的 GenericRepository。此外,我有一个 studentRepository,它使用通用存储库,但也具有独立于通用存储库的功能,我有一个名为 IStudentRepository 的接口。
这里是示例代码:
public interface IGenericEntityRepository<T>
{
Delete(T entity);
T Get(int id);
IEnumerable<T> GetAll();
Add(T entity);
Update(T entity);
}
public class GenericEntityRepository<T> : IGenericEntityRepository<T> where T : class
{
protected readonly ApplicationDbContext _applicationDbContext;
public GenericEntityRepository(ApplicationDbContext applicationDbContext)
{
this._applicationDbContext = applicationDbContext;
}
//Generic Repository Implementations....
}
public interface IStudentRepository
{
string GetFullName(Student student)
double GetGpa(Student student)
}
public class StudentRepository: GenericRepository<Student>, IStudentRepository
{
public StudentRepository(ApplicationDbContext applicationDbContext) : base(applicationDbContext)
{}
//IStudentRepository functions' implementations...
}
Now I need to inject this StudentRepository to my StudentsController
public class StudentsController : Controller
{
private readonly IGenericEntityRepository<Student> _genericStudentRepository;
public StudentsController(IGenericEntityRepository<Student> _genericStudentRepository)
{
this._genericStudentRepository = genericRepository;
}
public void testAccessibility()
{
this._genericStudentRepository.GetAll() //valid call
this._genericStudentRepository.GetAllGpa() //invalid Call
***As expected cause IGenericEntityRepository doesn't have that ***function
}
}
正如您在此处看到的问题,如果我注入 IGenericEntityRepository,我只会获得 genericrepository 功能。如果我想要不包含在 genericRepository 中的 Student 存储库的功能,我必须注入 IGenericEntityRepository 和 IStudentRepository,如下所示,反之亦然。
public class StudentsController : Controller
{
private readonly IGenericEntityRepository<Student> _genericStudentRepository;
private readonly IStudentRepository _studentsRepository;
public StudentsController(IGenericEntityRepository<Student> _genericStudentRepository, IStudentRepository studentsRepository)
{
this._genericStudentRepository = genericRepository;
this.__studentsRepository = studentsRepository;
}
public void testAccessibility()
{
this._genericStudentRepository.GetAll() //valid call
this._studentsRepository.GetAllGpa() //valid call
}
}
有没有更好的方法来做到这一点?像这样注入两个上下文相同但编码不同的对象感觉不对。
【问题讨论】:
标签: c# generics dependency-injection .net-core repository