工作单元模式(UnitOfWork)学习总结

本文是对工作单元模式的学习总结,该模式用于管理在业务交易中受到影响的对象并协调数据的持久化。以银行卡转账功能为例,介绍了如何设计和实现包括EntityBase基类、IUnitOfWork接口、IUnitOfWorkRepository接口、UnitOfWork实现、BankAccount实体、IAccountRepository接口、BankAccountService服务类以及AccountRepository和AccountRepositoryTest的测试。通过这个例子,展示了在实际操作中如何运用工作单元模式处理并发问题并确保数据一致性。
摘要由CSDN通过智能技术生成
工作单元的目标是维护变化的对象列表。使用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 IUnitOfW
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值