通用工作单元 [英] Generic Unit Of Work
问题描述
我已经实现了EntityFramework模式以及存储库和工作单元.该实现类似于代码项目存储库示例,但是我需要对工作单元进行增强.
I have implemented EntityFramework pattern along with Repository and Unit Of Work. The implementation is similar to Code Project Repository Example, however I need an enhancement for the Unit Of Work.
工作单位
public class GenericUnitOfWork : IDisposable
{
// Initialization code
public Dictionary<Type, object> repositories = new Dictionary<Type, object>();
public IRepository<T> Repository<T>() where T : class
{
if (repositories.Keys.Contains(typeof(T)) == true)
{
return repositories[typeof(T)] as IRepository<T>
}
IRepository<T> repo = new Repository<T>(entities);
repositories.Add(typeof(T), repo);
return repo;
}
// other methods
}
上面的UoW是一个安静的概括,它始终以父级Repository类为目标.我有另一个实体,例如学生,它有自己的存储库,该存储库扩展了Repository类.学生特定的存储库具有方法"GetStudentMarks()".现在,我无法使用常规的Unit of Work类,因为它始终指向父存储库.
The above UoW is quiet generalized and it targets the parent Repository class always. I have another entity, for example student, which has its own repository extending the Repository class. The student specific repository has a method "GetStudentMarks()". Now I cannot use the general Unit Of Work class since it always points to the parent Repository.
如何实施通用工作单位来处理此类情况?预先感谢.
How to implement a general Unit Of Work to handle such situations? Thanks in advance.
推荐答案
您可以使类 GenericUnitOfWork
泛型,并指定实体和存储库类型:
You can make the class GenericUnitOfWork
generics, specifying the entity and repository type:
public class GenericUnitOfWork<TRepo, TEntity> : IDisposable
where TRepo : Repository<TEntity>
{
// Initialization code
public Dictionary<Type, TRepo> repositories = new Dictionary<Type, TRepo>();
public TRepo Repository()
{
if (repositories.Keys.Contains(typeof(TEntity)) == true)
{
return repositories[typeof(TEntity)];
}
TRepo repo = (TRepo)Activator.CreateInstance(
typeof(TRepo),
new object[] { /*put there parameters to pass*/ });
repositories.Add(typeof(TEntity), repo);
return repo;
}
// other methods
}
类似的事情应该起作用.
Something like this should works.
这篇关于通用工作单元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!