工作单元模式(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个特性,也算是其功能: 使用同一上下文 跟踪实体的状态 保障事务一致性 工作单元模式 主要关注事务,所以重点在事务上. 在共享层的基础建设类库中 ...
随机推荐
- easyui 》 radio取值,checkbox取值,select取值,radio选中,checkbox选中,select选中
获取一组radio被选中项的值var item = $('input[@name=items][@checked]').val();获取select被选中项的文本var item = $(" ...
- 在android 6.0(API 23)中,Google已经移除了移除了Apache HttpClient相关的类
推荐使用HttpUrlConnection,如果要继续使用需要Apache HttpClient,需要在eclipse下libs里添加org.apache.http.legacy.jar,androi ...
- SSIS 错误
[OLE DB 源 [1]] 错误: SSIS 错误代码 DTS_E_OLEDBERROR.出现 OLE DB 错误.错误代码: 0x80040E14.已获得 OLE DB 记录.源:"Or ...
- javascript Xml兼容性随笔
一.前言 (function (window) { if (!window.jasen) { window.jasen = {}; } if (!window.jasen.core) { window ...
- nw.js 软件推荐:AxeSlide斧子演示:PPT的另一种可能(转)
AxeSlide斧子演示:PPT的另一种可能 一款简单有趣的演示文稿制作软件 AxeSlide斧子演示(www.axeslide.com),是一款简单有趣的演示文稿制作软件,基于H ...
- Spring RabbitMq概述
Spring AMQP consists of a handful of modules, each represented by a JAR in the distribution. These m ...
- Entity Framework 5.0系列之Code First数据库迁移
我们知道无论是"Database First"还是"Model First"当模型发生改变了都可以通过Visual Studio设计视图进行更新,那么对于Cod ...
- 如何为编程爱好者设计一款好玩的智能硬件(七)——LCD1602点阵字符型液晶显示模块驱动封装(上)
当前进展: 一.我的构想:如何为编程爱好者设计一款好玩的智能硬件(一)——即插即用.积木化.功能重组的智能硬件模块构想 二.别人家的孩子:如何为编程爱好者设计一款好玩的智能硬件(二)——别人是如何设计 ...
- CocoSocket开源下载与编写经验分享
CocoSocket分享 cocos2dx 3.1都出了,但依然没有发现与它原生的SOCKET支持,于是,这几天在家,手工撸了一个. 目前版本对IOS,ANDROID,WINDOWS支持良好.且为异步 ...
- java线程与并发(一)
有好几个月没写博客了,各种破事儿忙完,决定继续写博客,恰好最近想了解下有关Java并发的一些知识,所以就准备这一段时间,用零碎的时间多记录一点有关并发的知识.希望这次能一直坚持下去. 想了解并发,必须 ...