【发布时间】:2014-11-17 17:39:02
【问题描述】:
我的存储库模式是这样设置的:
public interface IRepository<T> where T : class {}
public abstract class Repository<C, T> : IRepository<T>
where C : DbContext, IBaseContext
where T : class, IEntity
{}
public interface ICustomerRepository : IRepository<Customer>
{//specific methods here}
public class CustomerRepository : Repository<MyContext, Customer>, ICustomerRepository
我在我的 UoW 类(和接口)中添加了以下方法:
public TRepository GetRepository<TEntity, TRepository>()
where TEntity : class, IEntity
where TRepository : IRepository<TEntity>
{
object[] args = new object[] { (IDatabaseFactory<MyContext>)databaseFactory };
return (TRepository)Activator.CreateInstance(typeof(TRepository), args);
}
在我的服务中,我尝试让存储库执行以下操作:
var customerRepository = uow.GetRepository<Customer, CustomerRepository>();
在 Autofac 中,我使用的是 InstancePerRequest。因此,UoW 和存储库实例是根据请求创建并在之后处理的。我还需要实现存储库的缓存吗?
这是使用存储库工厂的正确方法吗?
注意
我的 UoW 和存储库位于“DAL”程序集中,我的服务位于不同的“服务”程序集中。
【问题讨论】:
-
DbContext 已经缓存了查询结果。我认为,您应该将 UoW 中的缓存
IRepository实例添加到Dictionary<Type, object>中。 -
但是因为 UoW(以及存储库)在请求期间存在,我认为在 UoW 中实现存储库缓存是没有必要的(或有意义的)。
标签: c# asp.net-web-api repository-pattern