在資料存取層與業務邏輯層間建立抽象層,利於測試、解耦、可維護性。
public interface IStudentRepository : IDisposable {
IEnumerable<Student> GetStudents();
Student GetStudentByID(int id);
void InsertStudent(Student student);
void DeleteStudent(int studentID);
void UpdateStudent(Student student);
void Save();
}
public class StudentRepository : IStudentRepository {
private SchoolContext context;
public StudentRepository(SchoolContext context) { this.context = context; }
// 實作 CRUD 方法,Save() 呼叫 context.SaveChanges()
// 實作 Dispose 模式釋放 Context
}
UnitOfWork 類別封裝共享 SchoolContext,屬性暴露各 Repository 實例,Save() 統一提交,確保交易一致性。
private UnitOfWork unitOfWork = new UnitOfWork();
public ActionResult Index() { return View(unitOfWork.StudentRepository.GetStudents()); }
單元測試時可注入記憶體實作 (如 List<Student>),實現真正的 TDD。