谁能解释什么是 private readonly IStudentRepository _studentRepository?为什么被采取?

Bhu*_*ake 0 c# dependency-injection inversion-of-control asp.net-mvc-4

有两个文件:一个给出界面如下:

IStudentInterface.cs

 public interface IStudentService
{
    IEnumerable<Student> GetStudents();
    Student GetStudentById(int id);
    void CreateStudent(Student student);
    void UpdateStudent(Student student);
    void DeleteStudent(int id);
    void SaveStudent();
}
Run Code Online (Sandbox Code Playgroud)

学生服务.cs:

 public class StudentService : IStudentService
  {
    private readonly IStudentRepository _studentRepository;
    private readonly IUnitOfWork _unitOfWork;
    public StudentService(IStudentRepository studentRepository, IUnitOfWork unitOfWork)
    {
        this._studentRepository = studentRepository;
        this._unitOfWork = unitOfWork;
    }  
    #region IStudentService Members

    public IEnumerable<Student> GetStudents()
    {
        var students = _studentRepository.GetAll();
        return students;
    }

    public Student GetStudentById(int id)
    {
        var student = _studentRepository.GetById(id);
        return student;
    }

    public void CreateStudent(Student student)
    {
        _studentRepository.Add(student);
        _unitOfWork.Commit();
    }

    public void DeleteStudent(int id)
    {
        var student = _studentRepository.GetById(id);
        _studentRepository.Delete(student);
        _unitOfWork.Commit();
    }

    public void UpdateStudent(Student student)
    {
        _studentRepository.Update(student);
        _unitOfWork.Commit();
    }

    public void SaveStudent()
    {
        _unitOfWork.Commit();
    }

    #endregion
}
Run Code Online (Sandbox Code Playgroud)

请解释一下为什么_studentRepository要创建私有变量?我们也可以代替它来完成我们的任务。为什么所有这些事情都是这样完成的?请解释一下这个概念?

que*_*rin 5

IStudentRepositoryStudentService是对象执行其工作所依赖的一组功能(契约、抽象、服务 - 它可以采用各种术语) 。它还StudentService依赖于IUnitOfWork执行其工作。

private readonly IStudentRepository _studentRepository;是一个变量声明,用于存储实现合约的对象的实例。它是私有的,因为它只需要在类中访问StudentService,并且它是只读的,因为它是在类的构造函数中设置的,并且不需要在任何“StudentService”实例的生命周期中稍后进行修改。

控制反转的概念是,不是StudentService负责定位其依赖项的实现并实例化它们并管理它们的生命周期,而是由外部的一些其他代码承担StudentService这些职责。这是可取的,因为它减少了班级的担忧StudentService

为了更容易地应用控制反转,经常使用容器。容器提供了一种方式来说明接口或契约应使用哪些实现,并且还提供了自动提供这些实现的机制。最常见的方式是通过构造函数注入。IoC 容器将创建该类StudentService,并且还将创建构造该类所需的依赖项。在构造函数中,您可以将依赖项对象存储在类级变量中,以便在调用方法时可以使用它们来执行工作。