Here is my repository and unitofwork classes for our Asp.net MVC5(Entity Framework) application. I need to get instance of UnitOfWork class for each controller. But that means i need to get instance of all repository classes in my every controller even i dont need to use most of them in the controller.

For example, I need only one repository class in one of my controller, but in my approach, i need to get instances of all repository classes.

Is it the best approach ? Will it be a performance problem on production ?

Regards.

    public class UnitOfWork : IDisposable
    {
    private ApplicationDbContext db = new ApplicationDbContext();

    private WlbBookRepository wlbBookRepository;
    public WlbBookRepository WlbBookRepository
    {
        get
        {
            if (this.wlbBookRepository == null)
            {
                this.wlbBookRepository = new WlbBookRepository(db);
            }
            return wlbBookRepository;
        }
    }
    public void Save()
    {
        db.SaveChanges();
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                db.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

WlbBookRepository inherited from GenericRepository class as below:

public class WlbBookRepository : GenericRepository<WlbBook>
{
    private ApplicationDbContext db;

    public WlbBookRepository(ApplicationDbContext db) : base(db)
    {
        this.db = db;
    }
}

Generic Repository class

public class GenericRepository<TEntity> where TEntity : class , IBaseModel 
    {
        internal ApplicationDbContext context;
        internal DbSet<TEntity> dbSet;

        public GenericRepository(ApplicationDbContext context)
        {
            this.context = context;
            this.dbSet = context.Set<TEntity>();
        }
        public virtual TEntity GetByID(int? id)
        {
            return dbSet.Where(p=>p.Id == id).FirstOrDefault();
        }
        //All other generic methods.

}

And one of our controller

public class RfMasterController : Controller
{
    private UnitOfWork uow = new UnitOfWork();

    // GET: Rf/RfMaster
    public ActionResult Index()
    {
        return View(uow.RfMasterRepository.Get());
    }
}

Related posts

Recent Viewed