Repository 脱离了 IUnitOfWork,也有种小清新的感觉,Repository 的定义中说到,访问领域对象的集合,这个我们可以从 IDbContext 中进行操作,再来看一下 Application Service 中的代码:
public class StudentService : IStudentService { private IUnitOfWork _unitOfWork; private IStudentRepository _studentRepository; private ITeacherRepository _teacherRepository; public StudentService(IUnitOfWork unitOfWork, IStudentRepository studentRepository, ITeacherRepository teacherRepository) { _unitOfWork = unitOfWork; _studentRepository = studentRepository; _teacherRepository = teacherRepository; } public Student Get(int id) { return _studentRepository.Get(id); } public bool Add(string name) { var student = new Student { Name = name }; var teacher = _teacherRepository.Get(1); teacher.StudentCount++; _unitOfWork.RegisterNew(student); _unitOfWork.RegisterDirty(teacher); return _unitOfWork.Commit(); } }需要仔细看下 Add 中的方法,为了测试同一上下文中不同实体的操作,所以,我后面又增加了 Teacher 实体,因为这个方法比较有代表性,我大致分解下过程:
这个方法测试的主要目的是,通过 Repository 获取对象,并进行相应修改,然后用 UnitOfWork 提交修改,另外,在这个过程中,也会有其它对象的一些操作,测试是可行的,可以很好的避免之前修改 Student 需要通过 StudentRepository,修改 Teacher 需要通过 TeacherRepository,然后 Commit 两次,别问我为什么?因为我之前就这样干过。。。
最后的最后,附上测试代码:
public class StudentServiceTest { private IStudentService _studentService; public StudentServiceTest() { var container = new UnityContainer(); container.RegisterType<IDbContext, SchoolDbContext>(); container.RegisterType<IUnitOfWork, UnitOfWork>(); container.RegisterType<IStudentRepository, StudentRepository>(); container.RegisterType<ITeacherRepository, TeacherRepository>(); container.RegisterType<IStudentService, StudentService>(); _studentService = container.Resolve<IStudentService>(); } [Fact] public void GetByIdTest() { var student = _studentService.Get(1); Assert.NotNull(student); } [Fact] public void AddTest() { var result = _studentService.Add("xishuai"); Assert.True(result); } }posted @