.net-core - 工作单元 - 所有存储库都需要是属性吗?
问题描述
我正在尝试在 .net 核心项目中使用 Repository/UoW Pattern。我看过很多 web 上的实现。在所有实现中,存储库都是作为 IUnitOfWork 中的属性创建的。
在未来,如果我们有 50 个存储库,我们需要在工作单元中有 50 个属性。任何人都可以提出更好的方法来实现存储库/UoW。
请在下面找到我目前实施的方法的代码片段。
IUnitOfWork.cs
IStudentRepository Student { get; set; }
IClassRepository Class { get; set; }
void Complete();
UnitOfWORK.cs
public class unitofwork {
private readonly CollegeContext _context;
IStudentRepository Student { get; set; }
IClassRepository Class { get; set; }
public UnitOfWork(CollegeContext CollegeContext)
{
this._context = CollegeContext;
Student = new StudentRepository(_context);
Class = new ClassRepository(_context);
}
public void Complete()
{
return _context.SaveChanges();
}
}
Student 和 Class Repositories 分别从通用 Repository 类和 IStudentRepository 和 IClassRepository 继承。
StudentRepository.cs
public class StudentRepository : Repository<Student> , IStudentRepository
{
private readonly CollegeContext context;
private DbSet<Student> entities;
public StudentRepository(CollegeContext context) : base(context)
{
this.context = context;
entities = context.Set<Student>();
}
}
解决方案
正如您所说,在某些情况下,每个存储库的属性并不方便。我通常在 UoW 类中使用某种工厂方法,如下所示:
public class unitofwork
{
private readonly CollegeContext _context;
IStudentRepository Student { get; set; }
IClassRepository Class { get; set; }
public UnitOfWork(CollegeContext CollegeContext)
{
this._context = CollegeContext;
}
public T CreateRepository<T>() where T : IRepository
{
IRepository repository = null;
if(typeof(T) == typeof(IStudentRepository))
repository = new StudentRepository(_context);
......
......
else
throw new XyzException("Repository type is not handled.");
return (T)repository;
}
public void Complete()
{
return _context.SaveChanges();
}
}
public interface IRepository
{
Guid RepositoryId { get; }
}
我IRepository
只是持有一个简单的财产。您可以根据需要扩展此接口。
推荐阅读
- django - 通过 kwargs 和 FBV 中的查询字符串传递参数的 CBV 等效项是什么?
- angular - 将 Angular 项目从 7 升级到 8,现在无法在生产中运行
- sql - 查询在该行之前的给定时间范围 tr 中有 n 行的行
- python - 如何使用 python matplotlib 的艺术家层在条形图上显示百分比值
- c - 尝试在 C 中打印链接列表节点 - 仅打印最后一个节点?
- python - 如何解决 importError: no module named 'docX.api'; 'docx' 不是一个包
- javascript - 我无法将数据添加到 bootStrap 数据表
- java - 如何提高代码的性能?Java 中的 Selenium + JSON
- image - 检索网络资产时出错(颤振)
- ios - 我可以从 API 获取日期,但是当我填充单元格时,我的计数为零