使用存储库以工作模式为单位的.Net依赖项注入 [英] .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...
接口的定义 IRepository
显示为:
public interface IRepository
{
void Submit();
}
但是当接口用作<$ c定义的一部分时$ c> GenericRepository 类,则未实现Submit方法:
But when the interface is used as part of the definition of the GenericRepository
class, the Submit method is not implemented:
public abstract class GenericRepository<T> : IRepository<T> where T : class
{
public GenericRepository(IUnitOfWork unitOfWork)
{
unitOfWork.Register(this);
}
}
然后,定义特定实体的存储库类,继承自GenericRepository:
Then, a repository class for a specific entity is defined, inheriting from GenericRepository:
public class DepartmentRepository : GenericRepository<Department>
{
public DepartmentRepository(IUnitOfWork unitOfWork): base(unitOfWork) { }
}
我的问题是,鉴于每个不同实体的存储库可能都需要引用不同的 DataContext
,泛型 Submit( )
方法可以使用DI来实现?
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?
推荐答案
您链接到的问题是确保以下条件的解决方案:工作单位一直都知道存储库;仓库的实现本身是没有用的!存储库至少应公开所有杂项操作的方法:
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);
}
请参见此文章。
这篇关于使用存储库以工作模式为单位的.Net依赖项注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!