HTML5技术

DDD 领域驱动设计-谈谈 Repository、IUnitOfWork 和 IDbContext 的实践 - 田园里的(3)

字号+ 作者:H5之家 来源:博客园 2015-10-16 10:29 我要评论( )

Repository 脱离了 IUnitOfWork,也有种小清新的感觉,Repository 的定义中说到,访问领域对象的集合,这个我们可以从 IDbContext 中进行操作,再来看一下 Application Service 中的代码: public class StudentSer

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 @

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • 设计模式(1)单例模式(Singleton) - Fonour

    设计模式(1)单例模式(Singleton) - Fonour

    2017-04-23 12:00

  • 架构设计师能力模型 - BloodyAngel

    架构设计师能力模型 - BloodyAngel

    2017-03-28 11:00

  • 设计模式(0)简单工厂模式 - Fonour

    设计模式(0)简单工厂模式 - Fonour

    2017-03-25 15:01

  • 没有功能需求设计文档?对不起,拒绝开发! - CharlieChu

    没有功能需求设计文档?对不起,拒绝开发! - CharlieChu

    2017-03-16 13:04

网友点评
>