[英].Net Dependency injection in unit of work pattern using repositories
I'm a relative noob to the concept of Dependency Injection, and have been trying to glean the best practices before starting a new project. 对于依赖注入的概念,我是一个相对的菜鸟,在开始新项目之前,我一直在尝试收集最佳实践。
Looking at the top answer to Dependency injection in unit of work pattern using repositories I understand the approach, but the example code seems to be missing something, and I'm stumped... 在使用存储库的工作单元模式中查看依赖项注入的最佳答案,我理解了这种方法,但是示例代码似乎缺少了一些东西,我很困惑……
The definition of the interface IRepository
is shown as: 接口
IRepository
的定义如下所示:
public interface IRepository
{
void Submit();
}
But when the interface is used as part of the definition of the GenericRepository
class, the Submit method is not implemented: 但是,当将该接口用作
GenericRepository
类的定义的一部分时,将不会实现Submit方法:
public abstract class GenericRepository<T> : IRepository<T> where T : class
{
public GenericRepository(IUnitOfWork unitOfWork)
{
unitOfWork.Register(this);
}
}
Then, a repository class for a specific entity is defined, inheriting from GenericRepository: 然后,定义一个特定实体的存储库类,该类继承自GenericRepository:
public class DepartmentRepository : GenericRepository<Department>
{
public DepartmentRepository(IUnitOfWork unitOfWork): base(unitOfWork) { }
}
My question is, given that each different entity's repository may need a reference to a different DataContext
, how should the generic Submit()
method be implemented using DI? 我的问题是,鉴于每个不同实体的存储库都可能需要引用不同的
DataContext
,那么应该如何使用DI实现通用的Submit()
方法?
The question you link to was a solution to ensure that the Unit Of Work was always aware of Repositories; 您链接到的问题是一种确保工作单元始终了解存储库的解决方案; the repository implementation itself was pretty useless!
仓库的实现本身是没有用的! A Repository should, as a minimum, expose methods for all crud operations:
信息库至少应公开所有杂项操作的方法:
public interface IRepository<TEntity, in TKey> where TEntity : class
{
TEntity Read(TKey id);
TEntity Add(TEntity entity);
TEntity Update(TEntity entity);
void Delete(TKey id);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.