正确使用Repository Factory模式?

时间:2014-11-17 07:44:02

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

我的存储库模式设置如下:

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”程序集中,我的服务位于不同的“服务”程序集中。

1 个答案:

答案 0 :(得分:1)

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

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

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