简体   繁体   中英

What does the GenericRepository constructor do?

As per my understanding GenericRepository is inherited from IGenericRepository . It has properties as IDbFactory DbFactory , DBCustomerEntities dbContext and DBCustomerEntities DbContext . We are getting the value for DBCustomerEntities dbContext using Init method of IDbFactory , which is actually initialising database.

My question is why constructor GenericRepository is required and what is its role?

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?

Because you need to inject an implementation of IDbFactory into GenericRepository to let it work. Also, you're looking for abstracting how DbContext is instantiated using a factory, so you don't want to see how the factory is instantiated itself.

IMO, the actual usage of IDbFactory seems ugly to just avoid some lines, and it can be solved as follows (which, in fact, saves more lines!):

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>();
    .......

When you need to initialize something once only if you access it, you should use Lazy<T> .

There's another thing that looks less promising and it's that you're building a repository relying on IQueryable<T> . Please see this other Q&A: Repository design pattern to get more insights about this topic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM