Divyang Vyas
Divyang Vyas

Reputation: 65

MVC repository pattern with unit of work

I've implemented repository pattern with unit of work into an MVC app. Here is the implementation:

     public interface IUnitOfWork
    {
        IStudentRepository Students { get; }
        ICourseRepository Courses { get; }
        void Complete();
    }`
`    `
    public class UnitOfWork : IUnitOfWork
    {
        private readonly ApplicationDbContext _context;

        public IStudentRepository Students { get; private set; }
        public ICourseRepository Courses { get; private set; }

        public UnitOfWork(ApplicationDbContext context)
        {
            _context = context;
            Students = new StudentRepository(_context);
            Courses = new CourseRepository(_context);
        }

        public void Complete()
        {
            _context.SaveChanges();
        }
    }

` My question is, when I have 100s of repositories, what is the best approach to initiate a repository?

Thanks

Upvotes: 0

Views: 122

Answers (1)

Divyang Vyas
Divyang Vyas

Reputation: 65

I found the answer from one of the comments from this video: https://www.youtube.com/watch?v=rtXpYpZdOzM

Instead of initializing repositories in constructor, I can use getters like below:

public class UnitOfWork : IUnitOfWork
{
    private readonly ApplicationDbContext _context;

    private ICourseRepository _courses = null;
    private IStudentRepository _students = null;

    public UnitOfWork(ApplicationDbContext context)
    {
        _context = context;
    } 
  public ICourseRepository Courses => _courses ?? (_courses = new CourseRepository(_context));
public IStudentRepository Students => _students ?? (_students = new StudentRepository(_context));



Upvotes: 1

Related Questions