IAggregateRoot接口本身属于标记(market interface)接口模式。这个接口充当类和方法的元数据,那些与该类实例交互的代码在执行这些实例的工作之前检查是否存在该接口。
public interface IAggregateRoot{ };
IUnitOfWorkRepository是所有打算用在Unit of Work模式中的Repository需要实现的又一个接口。
public interface IUnitOfWorkRepository { void PersistCreationOf(IAggregateRoot entity); void PersistUpdateOf(IAggregateRoot entity); void PersistDeletionOf(IAggregateRoot entity); }
IUnitOfWork接口在注册修改、增加、删除时需要IUnitOfWorkRepository,这样在提交的时候,IUnitOfWork可以将真正的持久化方法的工作委托给适当的具体实现。
public interface IUnitOfWork { void RegisterAmended(IAggregateRoot entity, IUnitOfWorkRepository unitOfWorkRepository); void RegisterNew(IAggregateRoot entity, IUnitOfWorkRepository unitOfWorkRepository); void RegisterRemoved(IAggregateRoot entity, IUnitOfWorkRepository unitOfWorkRepository); void Commit(); }
public class UnitOfWork : IUnitOfWork { Dictionary<IAggregateRoot, IUnitOfWorkRepository> addedEntites; Dictionary<IAggregateRoot, IUnitOfWorkRepository> changedEntites; Dictionary<IAggregateRoot, IUnitOfWorkRepository> deletedEntites; public UnitOfWork() { addedEntites = new Dictionary<IAggregateRoot, IUnitOfWorkRepository>(); changedEntites = new Dictionary<IAggregateRoot, IUnitOfWorkRepository>(); deletedEntites = new Dictionary<IAggregateRoot, IUnitOfWorkRepository>(); } public void RegisterAmended(IAggregateRoot entity, IUnitOfWorkRepository unitOfWorkRepository) { if (!changedEntites.ContainsKey(entity)) { changedEntites.Add(entity, unitOfWorkRepository); } } public void RegisterNew(IAggregateRoot entity, IUnitOfWorkRepository unitOfWorkRepository) { if (!addedEntites.ContainsKey(entity)) { addedEntites.Add(entity, unitOfWorkRepository); } } public void RegisterRemoved(IAggregateRoot entity, IUnitOfWorkRepository unitOfWorkRepository) { if (!deletedEntites.ContainsKey(entity)) { deletedEntites.Add(entity, unitOfWorkRepository); } } public void Commit() { using (TransactionScope scope = new TransactionScope()) { foreach (IAggregateRoot entity in this.addedEntites.Keys) { this.addedEntites[entity].PersistCreationOf(entity); } foreach (IAggregateRoot entity in this.changedEntites.Keys) { this.addedEntites[entity].PersistUpdateOf(entity); } foreach (IAggregateRoot entity in this.deletedEntites.Keys) { this.addedEntites[entity].PersistDeletionOf(entity); } scope.Complete(); } } }