工作单元的目标是维护变化的对象列表。使用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框架如下设计:

代码实现如下:

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)学习总结的更多相关文章

  1. 仓储(Repository)和工作单元模式(UnitOfWork)

    仓储和工作单元模式 仓储模式 为什么要用仓储模式 通常不建议在业务逻辑层直接访问数据库.因为这样可能会导致如下结果: 重复的代码 编程错误的可能性更高 业务数据的弱类型 更难集中处理数据,比如缓存 无 ...

  2. MVC+EF 理解和实现仓储模式和工作单元模式

    MVC+EF 理解和实现仓储模式和工作单元模式 原文:Understanding Repository and Unit of Work Pattern and Implementing Generi ...

  3. Contoso 大学 - 9 - 实现仓储和工作单元模式

    原文 Contoso 大学 - 9 - 实现仓储和工作单元模式 By Tom Dykstra, Tom Dykstra is a Senior Programming Writer on Micros ...

  4. 演练5-8:Contoso大学校园管理系统(实现存储池和工作单元模式)

    在上一次的教程中,你已经使用继承来消除在 Student 和 Instructor 实体之间的重复代码.在这个教程中,你将要看到使用存储池和工作单元模式进行增.删.改.查的一些方法.像前面的教程一样, ...

  5. .NET应用架构设计—工作单元模式(摆脱过程式代码的重要思想,代替DDD实现轻量级业务)

    阅读目录: 1.背景介绍 2.过程式代码的真正困境 3.工作单元模式的简单示例 4.总结 1.背景介绍 一直都在谈论面向对象开发,但是开发企业应用系统时,使用面向对象开发最大的问题就是在于,多个对象之 ...

  6. [.NET领域驱动设计实战系列]专题四:前期准备之工作单元模式(Unit Of Work)

    一.前言 在前一专题中介绍了规约模式的实现,然后在仓储实现中,经常会涉及工作单元模式的实现.然而,在我的网上书店案例中也将引入工作单元模式,所以本专题将详细介绍下该模式,为后面案例的实现做一个铺垫. ...

  7. 关于工作单元模式——工作单元模式与EF结合的使用

    工作单元模式往往和仓储模式一起使用,本篇文章讲到的是工作单元模式和仓储模式一起用来在ef外面包一层,其实EF本身就是工作单元模式和仓储模式使用的经典例子,其中DbContext就是工作单元,而每个Db ...

  8. [.NET领域驱动设计实战系列]专题五:网上书店规约模式、工作单元模式的引入以及购物车的实现

    一.前言 在前面2篇博文中,我分别介绍了规约模式和工作单元模式,有了前面2篇博文的铺垫之后,下面就具体看看如何把这两种模式引入到之前的网上书店案例里. 二.规约模式的引入 在第三专题我们已经详细介绍了 ...

  9. 重新整理 .net core 实践篇—————工作单元模式[二十六]

    前言 简单整理一下工作单元模式. 正文 工作单元模式有3个特性,也算是其功能: 使用同一上下文 跟踪实体的状态 保障事务一致性 工作单元模式 主要关注事务,所以重点在事务上. 在共享层的基础建设类库中 ...

随机推荐

  1. 【MySQL】事务没有提交导致 锁等待Lock wait timeout exceeded异常

    异常:Lock wait timeout exceeded; try restarting transaction 解决办法:(需要数据库最高权限) 执行select * from informati ...

  2. 在Windows用Rebar来构建,编译,测试,发布Erlang项目

    rebar是一个遵循 Erlang/OTP 原则的 Erlang 项目构建工具,使用它可以减少构建标准 Erlang/OTP 项目架构配置的工作量,并且可以很容易的编译.测试.发布 Erlang 应用 ...

  3. 【TextBox】重写右键菜单

    参考资料 http://bbs.csdn.net/topics/390324356 http://www.cnblogs.com/ycxy/archive/2012/10/09/2716852.htm ...

  4. 【Hello CC.NET】巧用模板简化配置

    从 <[Hello CC.NET]CC.NET 实现自动化集成> 到 <[Hello CC.NET]自动化发布时 Web.config 文件维护> ,大神在评论里提到的方案还没 ...

  5. tcp/udp高并发和高吐吞性能测试工具

    在编写一个网络服务的时候都比较关心这个服务能达到多少并发连接,而在这连接的基础上又能达到一个怎样的交互能力.编写服务已经是一件很花力气的事情,而还要去编写一个能够体现结果的测试工具就更加消耗工作时间. ...

  6. 修改TFS2013服务账户或者密码

    修改TFS2013服务账户或者密码 TFS作为微软软件开发的全生命周期管理解决方案,可以很好的与windows的域管理结合使用,方便多系统下用户的管理和授权.如果TFS使用的服务账户设置的域账户密码过 ...

  7. Redhat Linux /etc/profile 与 /etc/bashrc 的区别

    最近学习RHCE,在umask这里,书里说要修改/etc/profile和/etc/bashrc两个文件,却没有说明这两个区别.于是在上网查看之后倒是明白了各是怎么用的./etc/profile是对应 ...

  8. 一个App完成入门篇(二)-搭建主框架

    通过第一课的学习,你已经掌握了如何通过debug调试器来跟PC上的设计器联调来实时查看UI设计效果.调试代码了,接下来通过一系列的demo开发教学你将很快上手学习到如何开发一个真正的App. 要开发A ...

  9. [.net 面向对象编程基础] (23) 结束语

    [.net 面向对象编程基础] (23)  结束语 这个系列的文章终于写完了,用了半个多月的时间,没有令我的粉丝们失望.我的感觉就是一个字累,两个字好累,三个字非常累.小伙伴们看我每篇博客的时间就知道 ...

  10. FusionCharts简单教程(六)------加载外部Logo

    一.加载外部文件Logo       在使用FusionCharts时,我们可能需要在加载图像的时候需要在图表中显示标识.图片等等.这里我们可以使用logoURL属性来实现.如: <chart ...