实体框架asp.net应用程序中的UOW和存储库

我刚刚开始阅读使用存储库和工作单元模式.我目前正在尝试在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意味着我不必将其传递给我的任何商业方法,并且可以同时与我的所有业务方法共享它.

这样做有什么缺点吗?还有更好的方法来实现这个吗?

解决方法

解决此问题的一种方法是使用依赖注入.通常,构造函数注入与单个入口点一起使用以解决依赖性.

public class MyBusinessService
{

   public MyBusinessService(Repository1 repository1,Repository2,uow u)
   {
        // assign the params to fields
   }

   public void businessMethod1()
   {
   }

   public void businessMethod1()
   {
   }
}

有很多流行的DI框架.选择你认为适合你的东西.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....