【问题标题】:Correct usage of Repository Factory pattern?正确使用存储工厂模式?
【发布时间】: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&lt;Type, object&gt; 中。
  • 但是因为 UoW(以及存储库)在请求期间存在,我认为在 UoW 中实现存储库缓存是没有必要的(或有意义的)。

标签: c# asp.net-web-api repository-pattern


【解决方案1】:

工厂的唯一工作是构造类的实例。所以从这个意义上说,你的工厂是正确的。

您的 IoC 容器已经在管理对象的生命周期,因此无需重复该工作。

我的问题是:为什么还要有工厂?您的 IoC 容器已经能够构建实例。为什么不直接从 Autofac 请求一个 ICustomerRepository 并让它为您构建,而不是请求一个自定义对象,该对象的唯一工作就是执行 Autofac 开箱即用的功能?

【讨论】:

  • Autofac 仅引用了 WebApi 项目,并且容器没有在各个层(服务、存储库等)之间传递,所以我决定采用上述解决方案。
  • 啊,我明白了。与所有模式一样,请记住在模式的原始定义和您需要它的目的之间找到平衡。因此,如果您的实施适合您,那么它就是正确的用法!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-29
  • 1970-01-01
  • 2016-12-24
  • 1970-01-01
相关资源
最近更新 更多