工作单元的目标是维护变化的对象列表。使用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();
}
}
}