user2017341
user2017341

Reputation: 175

How simplify creating repositories in class UnitOfWork?

Ignore the fact that DbContext in Entity Framework is unit of work right now. I wonder how I can simplify creating repositories in class UnitOfWork because now I must add property to that class each time when I create new repository class? I don't want generic repository class.

public class UnitOfWork
    {
        private SchoolContext _context = new SchoolContext();

        private IDepartmentRepository _departmentRepository;
        private ICourseRepository _courseRepository;

        public IDepartmentRepository DepartmentRepository
        {
            get
            {

                if (this._departmentRepository == null)
                {
                    this._departmentRepository = new DepartmentRepository(_context);
                }
                return _departmentRepository;
            }
        }

        public ICourseRepository CourseRepository
        {
            get
            {

                if (this._courseRepository == null)
                {
                    this._courseRepository = new CourseRepository(_context);
                }
                return _courseRepository;
            }
        }

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

    }

Upvotes: 1

Views: 109

Answers (1)

Athari
Athari

Reputation: 34295

It's your architecture, so you're the one responsible for providing properties for your repository types. There're several ways of simplifying your code:

  1. There's a shorter way of writing your properties:

    ICourseRepository _courseRepository;
    public ICourseRepository CourseRepository =>
        _courseRepository ?? (_courseRepository = new CourseRepository(_context));
    

    It'll be a little longer with C# 5 or lower (you'll need explicit get accessor). You can also use Lazy<T> type.

  2. Dependency injection. Your getter will look like this:

    _someDI.Get<ICourseRepository>(new Parameter(_context));
    

    You'll need to register your types first like this:

    _someDI.Register<ICourseRepository, CourseRepository>();
    

    or all types together:

    _someDI.RegisterAllImplementingInterface<IBaseRepository>().AsImplementingInterfaces();
    

    It'll also make using single method possible, though types will be less discoverable:

    TRep GetRepository<TRep>() where TRep : IBaseRepository =>
        _someDI.Get<TRep>(new Parameter(_context));
    
  3. Code generation using T4. You can read project files to get the list of types and then generate the properties based on that information.

  4. (Maybe) Code generation built into C# 7 when it becomes available. Whether it'll be available and what exactly will be incuded is still TBD.

Upvotes: 1

Related Questions