如何简化在 class UnitOfWork 中创建存储库?

How simplify creating repositories in class UnitOfWork?

忽略 Entity Framework 中的 DbContext 现在是工作单元这一事实。 我想知道如何简化在 class UnitOfWork 中创建存储库,因为现在我每次创建新存储库 class 时都必须向那个 class 添加 属性?我不想要通用存储库 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();
        }

    }

这是您的体系结构,因此您是负责为您的存储库类型提供属性的人。有几种方法可以简化您的代码:

  1. 有一种更短的属性编写方式:

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

    对于 C# 5 或更低版本,它会稍长一些(您需要显式获取访问器)。您也可以使用 Lazy<T> 类型。

  2. 依赖注入。您的 getter 将如下所示:

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

    您需要先像这样注册您的类型:

    _someDI.Register<ICourseRepository, CourseRepository>();
    

    或所有类型一起:

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

    它也会使使用单一方法成为可能,尽管类型会更不容易被发现:

    TRep GetRepository<TRep>() where TRep : IBaseRepository =>
        _someDI.Get<TRep>(new Parameter(_context));
    
  3. 使用 T4 生成代码。您可以读取项目文件以获取类型列表,然后根据该信息生成属性。

  4. (可能)C# 7 可用时内置代码生成。它是否可用以及具体包含什么仍待定。