我目前正在尝试实施存储库模式在我的 DbContext 之上。问题是,我最终遇到了一种情况,我必须将多个存储库注入到一个UnitOfWork
构造函数,像这样:
public class UnitOfWork
{
private DbContext _context;
ICustomerRepository Customers { get; private set; }
IEmployeeRepository Employees { get; private set; }
public UnitOfWork(DbContext context, ICustomerRepository cust, IEmployeeRepository emp)
{
_context = context;
Customers = cust;
Employees = emp;
}
}
但是,由于它们都必须共享相同的 DbContext,因此我看不到将它们注入作为一种选择。
这就是为什么我正在考虑创建一个RepositoryFactory
类,但由于所有存储库都继承自通用接口,我发现不可能创建单个存储库Create()
方法,因为毕竟它们没有真正的共同祖先作为有效的返回类型。
为了让您有更多的了解,这就是代码的样子:
public interface IRepository<TEntity> where TEntity:class
{
TEntity Get(int id);
IEnumerable<TEntity> GetAll();
}
public interface ICustomerRepository : IRepository<Customer>
{
IEnumerable<Customer> GetSeniorCustomers();
}
public class CustomerRepository : ICustomerRepository
{
private readonly DbContext _context;
public CustomerRepository(DbContext context) : base(context)
{
_context = context;
}
// ... implementation of ICustomerRepo here
}
现在,这就是目前的情况:
我希望能够做的是:
public UnitOfWork(DbContext context, RepositoryFactory fac)
{
_context = context;
Customers = fac.Create(context, RepoType.Customer);
Employees = fac.Create(context, RepoType.Employee);
}
我知道它并没有真正给我任何额外的灵活性,但在我看来,它确实让代码不那么笨重。
但是,正如我之前提到的,我想不出 Create() 方法的有效返回类型。
因此,我想出了在 RepositoryFactory 类中创建多个方法的想法,而不是单个参数化方法,如下所示:
public class RepositoryFactory
{
public ICustomerRepository CreateCustomerRepo(DbContext context){/*...*/}
public IEmployeeRepository CreateEmployeeRepo(DbContext context){/*...*/}
}
所以问题是:
- 我正在做的事情可以称为工厂方法吗?
- 如果不是,这至少是一个有效的解决方案吗?如果没有,我该如何达到同样的目的以更干净的方式?
By 达到同样的目的我的意思是实现一种以易于管理、简洁的方式创建这些存储库的方法。
感谢您提前提供的所有帮助。