我刚刚开始阅读使用存储库和工作单元模式.我目前正在尝试在asp.net Web表单应用程序中使用它与Entity Framework.但我有一个问题,我不确定我是否能够以一种简单的方式解释.
据我所知,工作单元用于封装业务事务.从我看到的示例中,以下列方式使用uow
businessMethod1() { uow u = new uow(); //instantiate unit of work repository1 rep1 = new repository1(uow); //instantiate repository1 repository2 rep2 = new repository2(uow); //instantiate repository1 rep1.dowork(); rep2.dowork(); u.save(); //save the changes made to the database. (effectively saving changes made //in both repository classes }
现在假设我有一个businessMethod2(),它类似于上面描述的方法.假设我想在businessMethod2()中使用businessMethod1(),这将是最佳实践.我想分享工作单位,所以我应该把它作为一个论点来传递?即改变上述方法
businessMethod1(uow u) { bool isNew = false; if (u == null) { u = new uow(); isNew = true; } repository1 rep1 = new repository1(uow); //instantiate repository1 repository2 rep2 = new repository2(uow); //instantiate repository1 rep1.dowork(); rep2.dowork(); if (isNew) u.save(); //save the changes made to the database. }
我在想更好的方法是使用单身人士哇.在每个页面请求中,都会创建一个新的uow实例,并由所有业务方法共享.在新请求中,将创建不同的实例.使用单身uow意味着我不必将其传递给我的任何商业方法,并且可以同时与我的所有业务方法共享它.
这样做有什么缺点吗?还有更好的方法来实现这个吗?