C# 正确使用存储库工厂模式?

C# 正确使用存储库工厂模式?,c#,asp.net-web-api,repository-pattern,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

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

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
公共接口i假设,其中T:class{}
公共抽象类存储库:IRepository
其中C:DbContext,IBaseContext
式中T:类,属性
{}
公共接口ICCustomerRepository:IRepository
{//此处的特定方法}
公共类CustomerRepository:存储库,ICCustomerRepository
我在UoW类(和接口)中添加了以下方法:

public TRepository GetRepository()
其中tenty:类,tenty
在哪里存储:i存储
{
对象[]args=新对象[]{(IDatabaseFactory)databaseFactory};
return(TRepository)Activator.CreateInstance(typeof(TRepository),args);
}
在我的服务中,我尝试让存储库执行以下操作:

var customerRepository = uow.GetRepository<Customer, CustomerRepository>();
var customerRepository=uow.GetRepository();
在Autofac中,我使用InstancePerRequest。因此,UoW和存储库实例是根据请求创建的,并在之后进行处理。我还需要实现存储库的缓存吗

这是使用存储库工厂的正确方法吗

注意


我的UoW和存储库位于“DAL”程序集中,我的服务位于不同的“服务”程序集中

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

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


我的问题是:为什么还要建工厂?您的IoC容器已经能够构造实例。为什么不直接从Autofac请求一个ICCustomerRepository并让它为您构建,而不是请求一个自定义对象,后者的唯一任务是做Autofac可以做的事情?

DbContext已经在缓存查询结果了。我认为,您应该将UoW中的缓存
IRepository
实例添加到
Dictionary
中。但是,由于UoW(以及存储库)在请求期间都处于活动状态,因此我认为在UoW中实现存储库缓存是不必要的(或者没有意义).Autofac仅在WebApi项目中引用,容器没有传递到各个层(服务、存储库等),因此我决定采用上述解决方案。啊,我明白了。与所有模式一样,记住它是关于在模式的原始定义和您需要它的目的之间找到平衡。因此,如果您的实现适合您,那么它就是正确的用法!
var customerRepository = uow.GetRepository<Customer, CustomerRepository>();