工作单元模式(UnitOfWork)学习总结

摘要:
维护业务部门预期的目标,并协调更改的写入和电流问题的解决方案。为了实现银行卡的简单转账功能,Demo框架设计如下:代码实现如下:EntityBase,域类的基类。ViewCodeIUnitOfWork用于以复杂的方式维护已更改的对象列表,最后提交、依次遍历已更改的列表并将其持久化。这就是Commit的作用。ViewCodeIUnitOfWorkRepository负责持久化对象。ViewCodeUnitOfWork,IUnitOfWork的具体实现。1使用系统;2使用System.Collections。通用的3使用系统。Linq;4使用系统。文本5使用System.Threading。任务;6使用系统。交易;78namespaceJack.Gao.UnitOfWork。基础结构9{10publicclassUnitOfWork:IUnitOfWork11{12#regionFields1314privateDictionary<EntityBase,IUnitOfWork Repository>addedEntities;15privateDicionary<EntityBase,IUnitOfWorkRepository>changedEntities,16privateDiction<EntityBase、IUnitOfWorks Repository>removedEntitments;1718#endregion1920#regionConstructor2122publicUnitOfWork()23{24addedEntities=newDictionary();25changededEntities=newDictionary());26removedEntities=newDicionary()4243publicvoidRegisterRemoved44{45this.removedEntities.Add;46}4748publicvoidCommit()49{50using51{52foreach53{54addedEntities〔实体〕。PersistNewItem;55}5657foreach58{59changededEntities(实体)。PersistUpdatedItem;60}6162 foreach63{64removedEn实体〕。PersistDeletedItem;65}6667transactionScope。Complete();68}69}7071#endregion72}73}BankAccount,继承自域基类EntityBase。

工作单元模式(UnitOfWork)学习总结

工作单元的目标是维护变化的对象列表。使用IUnitOfWorkRepository负责对象的持久化,使用IUnitOfWork收集变化的对象,并将变化的对象放到各自的增删改列表中,

最后Commit,Commit时需要循环遍历这些列表,并由Repository来持久化。

Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.

      要实现一个银行卡简单转账的功能,Demo框架如下设计:

      工作单元模式(UnitOfWork)学习总结第1张

      代码实现如下:

     

      EntityBase,领域类的基类。

     

工作单元模式(UnitOfWork)学习总结第2张 View Code

     IUnitOfWork,复杂维护变化的对象列表,并最后Commit,依次遍历变化的列表,并持久化,这就是Commit的事情。

工作单元模式(UnitOfWork)学习总结第3张 View Code

    

    IUnitOfWorkRepository,负责持久化对象。

   

工作单元模式(UnitOfWork)学习总结第4张 View Code

   

    UnitOfWork,IUnitOfWork的具体实现。

   

复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Transactions;
 7 
 8 namespace Jack.Gao.UnitOfWork.Infrastructure
 9 {
10     public class UnitOfWork:IUnitOfWork
11     {
12         #region Fields
13 
14         private Dictionary<EntityBase, IUnitOfWorkRepository> addedEntities;
15         private Dictionary<EntityBase, IUnitOfWorkRepository> changededEntities;
16         private Dictionary<EntityBase, IUnitOfWorkRepository> removedEntities;
17 
18         #endregion
19 
20         #region Constructor
21 
22         public UnitOfWork()
23         {
24             addedEntities=new Dictionary<EntityBase, IUnitOfWorkRepository>();
25             changededEntities=new Dictionary<EntityBase, IUnitOfWorkRepository>();
26             removedEntities=new Dictionary<EntityBase, IUnitOfWorkRepository>();
27         }
28 
29         #endregion
30 
31         #region Implement IUnitOfWork
32 
33         public void RegisterAdded(EntityBase entityBase, IUnitOfWorkRepository unitOfWorkRepository)
34         {
35             this.addedEntities.Add(entityBase,unitOfWorkRepository);
36         }
37 
38         public void RegisterChangeded(EntityBase entityBase, IUnitOfWorkRepository unitOfWorkRepository)
39         {
40             this.changededEntities.Add(entityBase,unitOfWorkRepository);
41         }
42 
43         public void RegisterRemoved(EntityBase entityBase, IUnitOfWorkRepository unitOfWorkRepository)
44         {
45             this.removedEntities.Add(entityBase,unitOfWorkRepository);
46         }
47 
48         public void Commit()
49         {
50             using (TransactionScope transactionScope=new TransactionScope())
51             {
52                 foreach (var entity in addedEntities.Keys)
53                 {
54                     addedEntities[entity].PersistNewItem(entity);
55                 }
56 
57                 foreach (var entity in changededEntities.Keys)
58                 {
59                     changededEntities[entity].PersistUpdatedItem(entity);
60                 }
61 
62                 foreach (var entity in removedEntities.Keys)
63                 {
64                     removedEntities[entity].PersistDeletedItem(entity);
65                 }
66 
67                 transactionScope.Complete();
68             }
69         }
70 
71         #endregion
72     }
73 }
复制代码


   

    BankAccount,继承自领域基类EntityBase。

   

工作单元模式(UnitOfWork)学习总结第7张 View Code

  

    IAccountRepository,持久化BankAcount接口

  

工作单元模式(UnitOfWork)学习总结第8张 View Code

   

    BankAccountService,服务类,实现转账服务。

复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using Jack.Gao.UnitOfWork.Infrastructure;
 7 
 8 namespace Jack.gao.UnitOfWork.Domain
 9 {
10     public class BankAccountService
11     {
12         #region Field
13 
14         private IAccountRepository _accountRepository;
15         private IUnitOfWork _unitOfWork;
16 
17         #endregion
18 
19         #region Constructor
20 
21         public BankAccountService(IAccountRepository accountRepository, IUnitOfWork unitOfWork)
22         {
23             this._accountRepository = accountRepository;
24             this._unitOfWork = unitOfWork;
25         }
26 
27         #endregion
28 
29         #region Method
30 
31         public void TransferMoney(BankAccount from, BankAccount to, decimal balance)
32         {
33             if (from.Balance>=balance)
34             {
35                 from.Balance = from.Balance - balance;
36                 to.Balance = to.Balance + balance;
37 
38                 _accountRepository.Save(from);
39                 _accountRepository.Save(to);
40                 _unitOfWork.Commit();
41             }
42         }
43 
44         #endregion
45     }
46 }
复制代码


    AccountRepository,持久化具体实现,使用ADO.NET实现,也可以使用其他的EF,NHbernate

复制代码
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Threading.Tasks;
  6 using Jack.gao.UnitOfWork.Domain;
  7 using Jack.Gao.UnitOfWork.Infrastructure;
  8 using System.Data.SqlClient;
  9 
 10 namespace Jack.gao.UnitOfWork.Persistence
 11 {
 12     public class AccountRepository:IAccountRepository,IUnitOfWorkRepository
 13     {
 14         #region Field
 15 
 16         private const string _connectionString = @"Data Source=T57649MSSQLSERVER2012;Initial Catalog=DB_Customer;Integrated Security=True";
 17 
 18         private IUnitOfWork _unitOfWork;
 19 
 20         #endregion
 21 
 22         #region Constructor
 23 
 24         public AccountRepository(IUnitOfWork unitOfWork)
 25         {
 26             this._unitOfWork = unitOfWork;
 27         }
 28 
 29         #endregion
 30 
 31         #region Implement interface IAccountRepository,IUnitOfWorkRepository
 32 
 33         public void Save(BankAccount account)
 34         {
 35             _unitOfWork.RegisterChangeded(account,this);
 36         }
 37 
 38         public void Add(BankAccount account)
 39         {
 40             _unitOfWork.RegisterAdded(account,this);
 41         }
 42 
 43         public void Remove(BankAccount account)
 44         {
 45             _unitOfWork.RegisterRemoved(account,this);
 46         }
 47 
 48         public void PersistNewItem(EntityBase entityBase)
 49         {
 50             BankAccount account = (BankAccount)entityBase;
 51 
 52             string insertAccountSql = string.Format("insert into DT_Account(balance,Id) values({0},{1})", account.Balance, account.Id);
 53 
 54             SqlConnection sqlConnection = new SqlConnection(_connectionString);
 55 
 56             try
 57             {
 58                 sqlConnection.Open();
 59 
 60                 SqlCommand sqlCommand = new SqlCommand(insertAccountSql, sqlConnection);
 61 
 62                 sqlCommand.ExecuteNonQuery();
 63             }
 64             catch (Exception ex)
 65             {
 66                 throw ex;
 67             }
 68             finally
 69             {
 70                 sqlConnection.Close();
 71             }
 72         }
 73 
 74         public void PersistUpdatedItem(EntityBase entityBase)
 75         {
 76             BankAccount account = (BankAccount)entityBase;
 77 
 78             string updateAccountSql = string.Format("update DT_Account set balance={0} where Id={1}", account.Balance,account.Id);
 79 
 80             SqlConnection sqlConnection = new SqlConnection(_connectionString);
 81 
 82             try
 83             {
 84                 sqlConnection.Open();
 85 
 86                 SqlCommand sqlCommand = new SqlCommand(updateAccountSql, sqlConnection);
 87 
 88                 sqlCommand.ExecuteNonQuery();
 89             }
 90             catch (Exception ex)
 91             {
 92                 throw ex;
 93             }
 94             finally
 95             {
 96                 sqlConnection.Close();
 97             }
 98         }
 99 
100         public void PersistDeletedItem(EntityBase entityBase)
101         {
102             BankAccount account = (BankAccount)entityBase;
103 
104             string deleteAccountSql = string.Format("delete from DT_Account where Id={0}", account.Id);
105 
106             SqlConnection sqlConnection = new SqlConnection(_connectionString);
107 
108             try
109             {
110                 sqlConnection.Open();
111 
112                 SqlCommand sqlCommand = new SqlCommand(deleteAccountSql, sqlConnection);
113 
114                 sqlCommand.ExecuteNonQuery();
115             }
116             catch (Exception ex)
117             {
118                 throw ex;
119             }
120             finally
121             {
122                 sqlConnection.Close();
123             }
124         }
125 
126         #endregion
127 
128         #region Method
129 
130         public BankAccount GetAccount(BankAccount account)
131         {
132             account.Balance = 100;
133             return account;
134         }
135 
136         #endregion
137     }
138 }
复制代码

    AccountRepositoryTest,测试AccountRepository中的方法

工作单元模式(UnitOfWork)学习总结第13张 View Code
 
 
分类: 设计模式

免责声明:文章转载自《工作单元模式(UnitOfWork)学习总结》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Magento入门开发教程十七、SAP中使用SQL语句读取一条数据下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

vue3.0打包后页面空白,放置服务器

lintOnSave:true,//配置跨域devServer:{open:true、host:'localhost'、port:3000、https:false,//以上IP地址和端口是我们计算机的本地地址;以下是需要跨域的代理:{//配置跨域名“/api”:{target:”http://106.12.148.51',//这里的背景地址是模拟的;您应该填...

.NET Core项目部署时自定义端口号

我会在有时间的时候总结Linux系统的部署。NETCore项目只使用这种方法。5.IIS部署项目。指定端口号环境:Windows。NET开发人员应该熟悉IIS吗。当我们使用IIS部署Core项目时,它与之前的Framework项目的部署类似。您可以自定义端口号。...

使用事务和SqlBulkCopy批量插入数据

类似与MicrosoftSQLServer包中名为bcp的命令行应用程序。但是使用SqlBulkCopy类可以编写托管代码解决方案,性能上优于bcp命令行应用程序,更优于如Insert方式向SQLServer表加载大量数据。SqlBulkCopy可以应用到大批量数据的转移上,而不管数据源是什么。之前在做winform开发的时候,发现当datagridview...

PowerQuery清理非文件名字符(清除指定列表中的所有字符)

在左侧导航窗格的空白区域右击,依次找到空白查询项接下来的思路是:遍历列表SearchList中的所有项,依次清理Data表中所有想要处理的列。第三个参数是一个函数:它告诉List.Accumulate函数,在每一次使用SearchList中某一项操作Data表时,其操作的方式是如何的。...

C# winform开发嵌套Chrome内核浏览器(WebKit.net)开发(一)

//Www.cnblogs.com/Maxq/p/6566558.htmlWebKit.net是WebKit的一个net包。使用它,。net程序可以非常方便地集成和使用webkit作为加载网页的容器。EventArgse){WebKit.WebKitBrowser=newWebKitBrowser();this.Controls.Add(浏览器);...

java android 读写西门子PLC数据,包含S7协议和Fetch/Write协议,s7支持200smart,300PLC,1200PLC,1500PLC

主要用于西门子PLC的M、Q、I、DB块的数据读写。该组件支持快速建立高性能Modbus TCP终端。对于日志记录,暂时只保留接口。具体来说,您可以为该组件支持的西门子通信实现两种协议。一种是S7协议,它几乎不需要PLC侧的参数配置。另一个是Fetch/Write协议,它有点麻烦。如果S7不方便阅读,您可以选择“获取/写入”。S7更方便。...