【问题标题】:MVC repository pattern with unit of work带有工作单元的 MVC 存储库模式
【发布时间】:2016-07-13 12:41:11
【问题描述】:

我已经在 MVC 应用程序中实现了带有工作单元的存储库模式。这是实现:

     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();
        }
    }

` 我的问题是,当我有 100 个存储库时,启动存储库的最佳方法是什么?

谢谢

【问题讨论】:

  • 实体框架已经是存储库的工作单元。为什么要重新发明轮子?

标签: model-view-controller repository-pattern unit-of-work


【解决方案1】:

我从该视频中的一位 cmet 中找到了答案:https://www.youtube.com/watch?v=rtXpYpZdOzM

我可以使用如下的 getter,而不是在构造函数中初始化存储库:

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));



【讨论】:

    猜你喜欢
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多