工作单元 - 所有存储库都需要是属性吗?

Unit of Work - All Repositories need to be properties?

我正在尝试在 .net 核心项目中使用 Repository/UoW 模式。我看过很多跨 web 的实现。在所有实现中,存储库都创建为 IUnitOfWork 中的属性。

将来如果我们有 50 个存储库,我们需要在工作单元中有 50 个属性。谁能提出一个更好的方法来实施 Repository/UoW.

请在下面找到我目前实现的方法的代码片段。

IUnitOfWork.cs

 IStudentRepository Student { get; set; }

        IClassRepository Class { get; set; }


        void Complete();

UnitOfWOrk.cs

public class unitofwork {

    private readonly CollegeContext _context;
            IStudentRepository Student { get; set; }

                IClassRepository Class { get; set; }
            public UnitOfWork(CollegeContext CollegeContext)
            {
                this._context = CollegeContext;
    Student =  new StudentRepository(_context);
    Class = new ClassRepository(_context);


            }

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

}

Student 和 Class 存储库分别继承自通用存储库 class 和 IStudentRepository 和 IClassRepository。

StudentRepository.cs

 public  class StudentRepository : Repository<Student>  , IStudentRepository
    {
        private readonly CollegeContext context;
        private DbSet<Student> entities;

        public StudentRepository(CollegeContext context) : base(context)
        {
            this.context = context;
            entities = context.Set<Student>();
        }
    }
正如您所说,

属性-per-Repository 在某些情况下并不方便。我通常在 UoW class 中使用某种工厂方法,如下所示:

public class unitofwork
{

    private readonly CollegeContext _context;
    IStudentRepository Student { get; set; }

    IClassRepository Class { get; set; }
    public UnitOfWork(CollegeContext CollegeContext)
    {
        this._context = CollegeContext;
    }

    public T CreateRepository<T>() where T : IRepository
    {
        IRepository repository = null;
        if(typeof(T) == typeof(IStudentRepository))
            repository = new StudentRepository(_context);
        ......
        ......
        else
            throw new XyzException("Repository type is not handled.");

        return (T)repository;
    }

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

public interface IRepository
{
    Guid RepositoryId { get; }
}

我的IRepository只是抱了个简单的属性。您可以根据需要扩展此接口。