工作单元示例
Unit of Work example
我读了这个页面:http://aspiringcraftsman.com/2015/11/01/survey-of-entity-framework-unit-of-work-patterns/
这很有趣。作者对该主题有很好的了解,但他不愿意向社区提供样本。
我想使用 "Injected Unit of Work Factory" 模式,但我不知道如何实现存储库。例如,我不知道应该在哪里创建 DbContext 以及在哪里调用 SaveChanges();
非常感谢任何帮助!
谢谢
考虑到正如其他人所说,DbContext
在实施该模式方面做得非常好,我会仔细考虑您是否应该实施工作单元模式的另一种实施。我一直在代码库中工作,人们在其中添加了额外的抽象,而您经常发现抽象对您没有好处,因为它们添加的问题至少与它们解决的问题一样多。考虑在需要时停止。
但是,您的问题的答案是;
- 弄清楚您的应用 'entry point' 在哪里。例如,对于 MVC 项目,它是一个控制器。
使用依赖注入创建您的条目points/controllers;
public CustomerController(CustomerService customerService)
{
this.customerService = customerService;
}
适当使用服务;
public ActionResult Edit(int id)
{
var model = this.customService.GetCustomer(id);
return View(model);
}
设置依赖注入,为您的工作单元提供正确的生命周期;
kernel.Bind<IUnitOfWork>().To<EntityFrameworkUnitOfWork>().InRequestScope();
kernel.Bind<ICustomerService().To<CustomerService>();
kernel.Bind<ICustomerRepository>().To<CustomerReposotory>();
然后当您创建一个 CustomerController 时,它会请求一个 CustomerService;请求一个 ICustomerRepostory,它请求 IUnitOfWork,它在整个请求中被赋予相同的上下文。
这不一定是我推荐的方法,但它是问题的答案!
我读了这个页面:http://aspiringcraftsman.com/2015/11/01/survey-of-entity-framework-unit-of-work-patterns/ 这很有趣。作者对该主题有很好的了解,但他不愿意向社区提供样本。
我想使用 "Injected Unit of Work Factory" 模式,但我不知道如何实现存储库。例如,我不知道应该在哪里创建 DbContext 以及在哪里调用 SaveChanges();
非常感谢任何帮助! 谢谢
考虑到正如其他人所说,DbContext
在实施该模式方面做得非常好,我会仔细考虑您是否应该实施工作单元模式的另一种实施。我一直在代码库中工作,人们在其中添加了额外的抽象,而您经常发现抽象对您没有好处,因为它们添加的问题至少与它们解决的问题一样多。考虑在需要时停止。
但是,您的问题的答案是;
- 弄清楚您的应用 'entry point' 在哪里。例如,对于 MVC 项目,它是一个控制器。
使用依赖注入创建您的条目points/controllers;
public CustomerController(CustomerService customerService) { this.customerService = customerService; }
适当使用服务;
public ActionResult Edit(int id) { var model = this.customService.GetCustomer(id); return View(model); }
设置依赖注入,为您的工作单元提供正确的生命周期;
kernel.Bind<IUnitOfWork>().To<EntityFrameworkUnitOfWork>().InRequestScope(); kernel.Bind<ICustomerService().To<CustomerService>(); kernel.Bind<ICustomerRepository>().To<CustomerReposotory>();
然后当您创建一个 CustomerController 时,它会请求一个 CustomerService;请求一个 ICustomerRepostory,它请求 IUnitOfWork,它在整个请求中被赋予相同的上下文。
这不一定是我推荐的方法,但它是问题的答案!