![](/img/trans.png)
[英]StructureMap select multiple constructor on GenericRepository
[英]What does the GenericRepository constructor do?
根據我的理解, GenericRepository
繼承自IGenericRepository
。 它具有IDbFactory DbFactory
, DBCustomerEntities dbContext
和DBCustomerEntities DbContext
。 我們所得到的值DBCustomerEntities dbContext
使用Init
的方法IDbFactory
,這實際上是初始化數據庫。
我的問題是為什么需要構造函數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>();
}
為什么需要構造函數GenericRepository?它的作用是什么?
因為您需要將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>
的存儲庫。 請參閱其他“問答: 存儲庫”設計模式,以獲取有關此主題的更多見解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.