簡體   English   中英

GenericRepository構造函數做什么?

[英]What does the GenericRepository constructor do?

根據我的理解, GenericRepository繼承自IGenericRepository 它具有IDbFactory DbFactoryDBCustomerEntities dbContextDBCustomerEntities 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM