工作单元模式(UnitOfWork)学习总结
工作单元的目标是维护变化的对象列表。使用IUnitOfWorkRepository负责对象的持久化,使用IUnitOfWork收集变化的对象,并将变化的对象放到各自的增删改列表中,
最后Commit,Commit时需要循环遍历这些列表,并由Repository来持久化。
要实现一个银行卡简单转账的功能,Demo框架如下设计:

代码实现如下:
EntityBase,领域类的基类。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Jack.Gao.UnitOfWork.Infrastructure
{
public class EntityBase
{ }
}
IUnitOfWork,复杂维护变化的对象列表,并最后Commit,依次遍历变化的列表,并持久化,这就是Commit的事情。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Jack.Gao.UnitOfWork.Infrastructure
{
public interface IUnitOfWork
{
void RegisterAdded(EntityBase entityBase, IUnitOfWorkRepository unitOfWorkRepository);
void RegisterChangeded(EntityBase entityBase, IUnitOfWorkRepository unitOfWorkRepository);
void RegisterRemoved(EntityBase entityBase, IUnitOfWorkRepository unitOfWorkRepository);
void Commit();
}
}
IUnitOfWorkRepository,负责持久化对象。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Jack.Gao.UnitOfWork.Infrastructure
{
public interface IUnitOfWorkRepository
{
void PersistNewItem(EntityBase entityBase);
void PersistUpdatedItem(EntityBase entityBase);
void PersistDeletedItem(EntityBase entityBase);
}
}
UnitOfWork,IUnitOfWork的具体实现。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions; namespace Jack.Gao.UnitOfWork.Infrastructure
{
public class UnitOfWork:IUnitOfWork
{
#region Fields private Dictionary<EntityBase, IUnitOfWorkRepository> addedEntities;
private Dictionary<EntityBase, IUnitOfWorkRepository> changededEntities;
private Dictionary<EntityBase, IUnitOfWorkRepository> removedEntities; #endregion #region Constructor public UnitOfWork()
{
addedEntities=new Dictionary<EntityBase, IUnitOfWorkRepository>();
changededEntities=new Dictionary<EntityBase, IUnitOfWorkRepository>();
removedEntities=new Dictionary<EntityBase, IUnitOfWorkRepository>();
} #endregion #region Implement IUnitOfWork public void RegisterAdded(EntityBase entityBase, IUnitOfWorkRepository unitOfWorkRepository)
{
this.addedEntities.Add(entityBase,unitOfWorkRepository);
} public void RegisterChangeded(EntityBase entityBase, IUnitOfWorkRepository unitOfWorkRepository)
{
this.changededEntities.Add(entityBase,unitOfWorkRepository);
} public void RegisterRemoved(EntityBase entityBase, IUnitOfWorkRepository unitOfWorkRepository)
{
this.removedEntities.Add(entityBase,unitOfWorkRepository);
} public void Commit()
{
using (TransactionScope transactionScope=new TransactionScope())
{
foreach (var entity in addedEntities.Keys)
{
addedEntities[entity].PersistNewItem(entity);
} foreach (var entity in changededEntities.Keys)
{
changededEntities[entity].PersistUpdatedItem(entity);
} foreach (var entity in removedEntities.Keys)
{
removedEntities[entity].PersistDeletedItem(entity);
} transactionScope.Complete();
}
} #endregion
}
}
BankAccount,继承自领域基类EntityBase。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using Jack.Gao.UnitOfWork.Infrastructure; namespace Jack.gao.UnitOfWork.Domain
{
public class BankAccount:EntityBase
{
#region Field public int Id { get; set; } public decimal Balance { get; set; } #endregion #region operator + public static BankAccount operator+(BankAccount accountLeft,BankAccount accountRight)
{
BankAccount account = new BankAccount(); account.Balance = accountLeft.Balance + accountRight.Balance; return account;
} #endregion
}
}
IAccountRepository,持久化BankAcount接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Jack.gao.UnitOfWork.Domain
{
public interface IAccountRepository
{
void Save(BankAccount account);
void Add(BankAccount account);
void Remove(BankAccount account);
}
}
BankAccountService,服务类,实现转账服务。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Jack.Gao.UnitOfWork.Infrastructure; namespace Jack.gao.UnitOfWork.Domain
{
public class BankAccountService
{
#region Field private IAccountRepository _accountRepository;
private IUnitOfWork _unitOfWork; #endregion #region Constructor public BankAccountService(IAccountRepository accountRepository, IUnitOfWork unitOfWork)
{
this._accountRepository = accountRepository;
this._unitOfWork = unitOfWork;
} #endregion #region Method public void TransferMoney(BankAccount from, BankAccount to, decimal balance)
{
if (from.Balance>=balance)
{
from.Balance = from.Balance - balance;
to.Balance = to.Balance + balance; _accountRepository.Save(from);
_accountRepository.Save(to);
_unitOfWork.Commit();
}
} #endregion
}
}
AccountRepository,持久化具体实现,使用ADO.NET实现,也可以使用其他的EF,NHbernate
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Jack.gao.UnitOfWork.Domain;
using Jack.Gao.UnitOfWork.Infrastructure;
using System.Data.SqlClient; namespace Jack.gao.UnitOfWork.Persistence
{
public class AccountRepository:IAccountRepository,IUnitOfWorkRepository
{
#region Field private const string _connectionString = @"Data Source=T57649\MSSQLSERVER2012;Initial Catalog=DB_Customer;Integrated Security=True"; private IUnitOfWork _unitOfWork; #endregion #region Constructor public AccountRepository(IUnitOfWork unitOfWork)
{
this._unitOfWork = unitOfWork;
} #endregion #region Implement interface IAccountRepository,IUnitOfWorkRepository public void Save(BankAccount account)
{
_unitOfWork.RegisterChangeded(account,this);
} public void Add(BankAccount account)
{
_unitOfWork.RegisterAdded(account,this);
} public void Remove(BankAccount account)
{
_unitOfWork.RegisterRemoved(account,this);
} public void PersistNewItem(EntityBase entityBase)
{
BankAccount account = (BankAccount)entityBase; string insertAccountSql = string.Format("insert into DT_Account(balance,Id) values({0},{1})", account.Balance, account.Id); SqlConnection sqlConnection = new SqlConnection(_connectionString); try
{
sqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand(insertAccountSql, sqlConnection); sqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlConnection.Close();
}
} public void PersistUpdatedItem(EntityBase entityBase)
{
BankAccount account = (BankAccount)entityBase; string updateAccountSql = string.Format("update DT_Account set balance={0} where Id={1}", account.Balance,account.Id); SqlConnection sqlConnection = new SqlConnection(_connectionString); try
{
sqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand(updateAccountSql, sqlConnection); sqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlConnection.Close();
}
} public void PersistDeletedItem(EntityBase entityBase)
{
BankAccount account = (BankAccount)entityBase; string deleteAccountSql = string.Format("delete from DT_Account where Id={0}", account.Id); SqlConnection sqlConnection = new SqlConnection(_connectionString); try
{
sqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand(deleteAccountSql, sqlConnection); sqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlConnection.Close();
}
} #endregion #region Method public BankAccount GetAccount(BankAccount account)
{
account.Balance = ;
return account;
} #endregion
}
}
AccountRepositoryTest,测试AccountRepository中的方法
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Jack.gao.UnitOfWork.Domain;
using Jack.Gao.UnitOfWork.Infrastructure;
using Jack.gao.UnitOfWork.Persistence; namespace Jack.gao.UnitOfWork.Test
{
[TestClass]
public class AccountRepositoryTest
{
private IUnitOfWork unitOfWork;
private IAccountRepository accountRepository;
private BankAccountService accountService; public AccountRepositoryTest()
{
unitOfWork = new Jack.Gao.UnitOfWork.Infrastructure.UnitOfWork();
accountRepository = new AccountRepository(unitOfWork);
accountService = new BankAccountService(accountRepository, unitOfWork);
} [TestMethod]
public void Add()
{
var accountLeft = new BankAccount() { Balance = , Id = };
var accountRight = new BankAccount() { Balance = , Id = }; accountRepository.Add(accountLeft);
accountRepository.Add(accountRight); unitOfWork.Commit();
} [TestMethod]
public void Save()
{
var accountLeft = new BankAccount() { Balance = , Id = };
var accountRight = new BankAccount() { Balance = , Id = }; accountService.TransferMoney(accountLeft, accountRight, );
} [TestMethod]
public void Remove()
{
var accountLeft = new BankAccount() { Balance = , Id = }; accountRepository.Remove(accountLeft); unitOfWork.Commit();
}
}
}
工作单元模式(UnitOfWork)学习总结的更多相关文章
- 仓储(Repository)和工作单元模式(UnitOfWork)
仓储和工作单元模式 仓储模式 为什么要用仓储模式 通常不建议在业务逻辑层直接访问数据库.因为这样可能会导致如下结果: 重复的代码 编程错误的可能性更高 业务数据的弱类型 更难集中处理数据,比如缓存 无 ...
- MVC+EF 理解和实现仓储模式和工作单元模式
MVC+EF 理解和实现仓储模式和工作单元模式 原文:Understanding Repository and Unit of Work Pattern and Implementing Generi ...
- Contoso 大学 - 9 - 实现仓储和工作单元模式
原文 Contoso 大学 - 9 - 实现仓储和工作单元模式 By Tom Dykstra, Tom Dykstra is a Senior Programming Writer on Micros ...
- 演练5-8:Contoso大学校园管理系统(实现存储池和工作单元模式)
在上一次的教程中,你已经使用继承来消除在 Student 和 Instructor 实体之间的重复代码.在这个教程中,你将要看到使用存储池和工作单元模式进行增.删.改.查的一些方法.像前面的教程一样, ...
- .NET应用架构设计—工作单元模式(摆脱过程式代码的重要思想,代替DDD实现轻量级业务)
阅读目录: 1.背景介绍 2.过程式代码的真正困境 3.工作单元模式的简单示例 4.总结 1.背景介绍 一直都在谈论面向对象开发,但是开发企业应用系统时,使用面向对象开发最大的问题就是在于,多个对象之 ...
- [.NET领域驱动设计实战系列]专题四:前期准备之工作单元模式(Unit Of Work)
一.前言 在前一专题中介绍了规约模式的实现,然后在仓储实现中,经常会涉及工作单元模式的实现.然而,在我的网上书店案例中也将引入工作单元模式,所以本专题将详细介绍下该模式,为后面案例的实现做一个铺垫. ...
- 关于工作单元模式——工作单元模式与EF结合的使用
工作单元模式往往和仓储模式一起使用,本篇文章讲到的是工作单元模式和仓储模式一起用来在ef外面包一层,其实EF本身就是工作单元模式和仓储模式使用的经典例子,其中DbContext就是工作单元,而每个Db ...
- [.NET领域驱动设计实战系列]专题五:网上书店规约模式、工作单元模式的引入以及购物车的实现
一.前言 在前面2篇博文中,我分别介绍了规约模式和工作单元模式,有了前面2篇博文的铺垫之后,下面就具体看看如何把这两种模式引入到之前的网上书店案例里. 二.规约模式的引入 在第三专题我们已经详细介绍了 ...
- 重新整理 .net core 实践篇—————工作单元模式[二十六]
前言 简单整理一下工作单元模式. 正文 工作单元模式有3个特性,也算是其功能: 使用同一上下文 跟踪实体的状态 保障事务一致性 工作单元模式 主要关注事务,所以重点在事务上. 在共享层的基础建设类库中 ...
随机推荐
- Android 适配2
Android AutoLayout全新的适配方式 堪称适配终结者 转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/4999094 ...
- onBlur事件与onfocus事件(js)
onFocus事件就是当光标落在文本框中时发生的事件. onBlur事件是光标失去焦点时发生的事件. 可以编如下例子 1.html <HTML><HEAD><TITL ...
- 【C-循环结构】
C语言提供了多种循环语句,可以组成各种不同形式的循环结构: 用goto语句和if语句构成循环: 用while语句: 用do-while语句: 用for语句: 一.goto语句 goto语句是一种无条件 ...
- easyui的datagrid打印(转)
在使用easyui插件的时候,使用最多的应该是datagrid插件.有时候根据客户需求,可能需要将datagrid内容进行打印,这时候如果直接调用window.print,可能由于easyui的dat ...
- 【转】WIN32 控制台程序
http://blog.csdn.net/houmin0036/article/details/7702236 win32控制台项目指在32位Windows命令提示符(即所谓的dos)环境下运行的应用 ...
- Zabbix日志监视的汇总报警(更新发送邮件脚本)
Zabbix的用户一定会碰到这种情况: 日志报警一般设置的是multiple模式,有错误大量写入的时候,每写入一行就会触发一次action,导致出现大量的报警邮件. 特别是ora的报警,经常一出就是上 ...
- 关于div弹出层的实际应用心得
今天本人要做一个点击弹出的功能,因为这个功能是最后做的,所以写的时候很纠结, 因为本人小菜一枚, 开始尝试用 position:relative:来做一试不行呀 ,因为用这个来做的话 会打乱原有的布局 ...
- android precelable和Serialization序列化数据传输
一 序列化原因: 1.永久性保存对象,保存对象的字节序列到本地文件中:2.通过序列化对象在网络中传递对象:3.通过序列化在进程间传递对象. 二 至于选取哪种可参考下面的原则: 1.在使用内存的时候,P ...
- 用Razor做静态页面生成器
本来是用asp.net webpages做的博客网站,数据库用了一个陌生的本地数据库,只是觉得用起来很爽快,用新鲜的东西有一种刺激.后来数据库挂了,估计是存某个字段的时候出了问题,可是新鲜的东西,也不 ...
- .NET Framework3.0/3.5/4.0/4.5新增功能摘要
Microsoft .NET Framework 3.0 .NET Framework 3.0 中增加了不少新功能,例如: Windows Workflow Foundation (WF) Windo ...