GenericRepository 构造函数的作用是什么?
What does the GenericRepository constructor do?
据我了解GenericRepository
是继承自IGenericRepository
。它具有 IDbFactory DbFactory
、DBCustomerEntities dbContext
和 DBCustomerEntities DbContext
的属性。我们正在使用 IDbFactory
的 Init
方法获取 DBCustomerEntities dbContext
的值,这实际上是初始化数据库。
我的问题是为什么需要构造函数 GenericRepository
,它的作用是什么?
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
private DBCustomerEntities dbContext;
protected IDbFactory DbFactory
{ get; private set; }
protected DBCustomerEntities DbContext
{
get { return dbContext ?? (dbContext = DbFactory.Init()); }
}
public GenericRepository(IDbFactory dbFactory)
{
DbFactory = dbFactory;
}
public IQueryable<T> GetAll()
{
return DbContext.Set<T>();
}
why constructor GenericRepository is required and what is it's role?
因为你需要将 IDbFactory
的实现注入到 GenericRepository
中才能让它工作。此外,您正在寻找抽象 如何 DbContext
是使用工厂实例化的,因此您不想看到工厂是如何实例化自身的。
IMO, IDbFactory
的实际用法似乎很难看,只是避免了一些行,可以按如下方式解决(实际上可以节省更多行!):
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
public GenericRepository(IDbFactory dbFactory)
{
DbContext = new Lazy<DBCustomerEntities>(dbFactory.Init);
}
protected Lazy<DBCustomerEntities> DbContext { get; }
public IQueryable<T> GetAll() => DbContext.Value.Set<T>();
.......
当你只需要在访问某物时初始化一次,你应该使用Lazy<T>
。
还有一件事看起来不太乐观,那就是您正在构建依赖于 IQueryable<T>
的存储库。请参阅其他问答:Repository design pattern 以获得有关此主题的更多见解。
据我了解GenericRepository
是继承自IGenericRepository
。它具有 IDbFactory DbFactory
、DBCustomerEntities dbContext
和 DBCustomerEntities DbContext
的属性。我们正在使用 IDbFactory
的 Init
方法获取 DBCustomerEntities dbContext
的值,这实际上是初始化数据库。
我的问题是为什么需要构造函数 GenericRepository
,它的作用是什么?
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
private DBCustomerEntities dbContext;
protected IDbFactory DbFactory
{ get; private set; }
protected DBCustomerEntities DbContext
{
get { return dbContext ?? (dbContext = DbFactory.Init()); }
}
public GenericRepository(IDbFactory dbFactory)
{
DbFactory = dbFactory;
}
public IQueryable<T> GetAll()
{
return DbContext.Set<T>();
}
why constructor GenericRepository is required and what is it's role?
因为你需要将 IDbFactory
的实现注入到 GenericRepository
中才能让它工作。此外,您正在寻找抽象 如何 DbContext
是使用工厂实例化的,因此您不想看到工厂是如何实例化自身的。
IMO, IDbFactory
的实际用法似乎很难看,只是避免了一些行,可以按如下方式解决(实际上可以节省更多行!):
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
public GenericRepository(IDbFactory dbFactory)
{
DbContext = new Lazy<DBCustomerEntities>(dbFactory.Init);
}
protected Lazy<DBCustomerEntities> DbContext { get; }
public IQueryable<T> GetAll() => DbContext.Value.Set<T>();
.......
当你只需要在访问某物时初始化一次,你应该使用Lazy<T>
。
还有一件事看起来不太乐观,那就是您正在构建依赖于 IQueryable<T>
的存储库。请参阅其他问答:Repository design pattern 以获得有关此主题的更多见解。