【问题标题】:MVC Interface and Repository DifferenceMVC 接口和存储库的区别
【发布时间】:2018-05-08 03:14:46
【问题描述】:

我注意到人们创建 1) 接口和 2) 存储库的代码。 Interface 列出了所有数据 Crud 操作,而 Repository 实际上定义了数据 Crud 操作。为什么不把它们组合成一个类呢?我听说这是抽象级别的东西?为什么他们在两个不同的地方?我是初学者,所以试图学习分离。谢谢,

资源:Implementing RepositoryImplement Repository Pattern

namespace ContosoUniversity.DAL
{
    public interface IStudentRepository : IDisposable
    {
        IEnumerable<Student> GetStudents();
        Student GetStudentByID(int studentId);
        void InsertStudent(Student student);
        void DeleteStudent(int studentID);
        void UpdateStudent(Student student);
        void Save();
    }
}


namespace ContosoUniversity.DAL
{
    public class StudentRepository : IStudentRepository, IDisposable
    {
        private SchoolContext context;

        public StudentRepository(SchoolContext context)
        {
            this.context = context;
        }

        public IEnumerable<Student> GetStudents()
        {
            return context.Students.ToList();
        }

        public Student GetStudentByID(int id)
        {
            return context.Students.Find(id);
        }

        public void InsertStudent(Student student)
        {
            context.Students.Add(student);
        }

        public void DeleteStudent(int studentID)
        {
            Student student = context.Students.Find(studentID);
            context.Students.Remove(student);
        }

        public void UpdateStudent(Student student)
        {
            context.Entry(student).State = EntityState.Modified;
        }

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

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}

【问题讨论】:

    标签: c# model-view-controller asp.net-core interface repository


    【解决方案1】:

    通过定义一个接口,你的仓库的消费者,可能是一个Controller类,只需要依赖你的接口IStudentRepository并且是loosely coupled。这遵循Dependency Inversion Principle。您可以从Dependency Injection 的主题中阅读有关这些概念的更多信息。

    它的一个特定用例是,如果有一天您决定更改存储库中 CRUD 操作的实现细节,您可以注册此新服务,并且不需要在存储库的消费者端进行任何更改(假设您正在使用依赖注入服务)。

    【讨论】:

    • 你的意思不是“可能是一个Controller类,只需要依赖Repository”吗?在 MSDN 示例中,控制器依赖于存储库
    • 我的意思是Controller依赖于你的IStudentRepository,而不是StudentRepository
    • 您链接的 MSDN 文章没有使用依赖注入服务,也不会充分展示这种模式的好处。但是,在您链接的第二篇文章中,最后一部分确实经历了依赖注入。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 2010-11-29
    • 2016-05-01
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多