当前位置:网站首页>Castle.DynamicProxy实现事务单元控制
Castle.DynamicProxy实现事务单元控制
2022-04-23 11:31:00 【驾驭人生】
using System;
using System.Collections.Generic;
using System.Text;
namespace Initial.Extensions
{
/// <summary>
/// 工作单元
/// 仅用来做特性标记
/// </summary>
public class UnitOfWorkAttribute : Attribute
{
}
}
using Castle.DynamicProxy;
using Microsoft.AspNetCore.Http;
using DataCommon.UnitOfWork;
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace Initial
{
public class UnitOfWorkIInterceptor : IInterceptor
{
#region 必须的
private readonly ILogger _logger;
private readonly IUnitOfWork _unitOfWork;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly HttpContext _httpContext;
#endregion
public UnitOfWorkIInterceptor(
ILogger logger,
IUnitOfWork unitOfWork,
IHttpContextAccessor httpContextAccessor
)
{
_logger = logger;
_unitOfWork = unitOfWork;
_httpContextAccessor = httpContextAccessor;
_httpContext = httpContextAccessor.HttpContext;
}
public void Intercept(IInvocation invocation)
{
MethodInfo methodInfo = invocation.MethodInvocationTarget;
if (methodInfo == null)
methodInfo = invocation.Method;
UnitOfWorkAttribute transaction = methodInfo.GetCustomAttributes<UnitOfWorkAttribute>(true).FirstOrDefault();
//如果标记了 [UnitOfWork],并且不在事务嵌套中。
if (transaction != null)
{
try
{
//开启事务
_unitOfWork.BeginTransaction();
invocation.Proceed();
//提交事务
var result = ((Task<bool>)invocation.ReturnValue).Result;
_unitOfWork.Commit();
}
catch (Exception ex)
{
//回滚
_unitOfWork.Rollback();
_logger.Info($"[{(_httpContextAccessor.HttpContext ?? _httpContext)?.TraceIdentifier}]" +
$"_{methodInfo.Name}执行异常{ex.ToString()}");
throw new BusinessException("提交异常");
}
}
else
{
//如果没有标记[UnitOfWork],直接执行方法
invocation.Proceed();
}
}
}
}
using Castle.Core;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Repository
{
[Interceptor(typeof(UnitOfWorkIInterceptor))]
public class TemplateRepository : ITemplateRepository
{
#region 必须的
private readonly ILogger _logger;
private readonly IDBInstance _IDBInstance;
#endregion
public TemplateRepository(
ILogger logger,
IDBInstance IDBInstance
)
{
_logger = logger;
_IDBInstance = IDBInstance;
}
#region 单表增删改查规范
#endregion
#region 多表操作
[UnitOfWork]
public async Task<bool> AddTepWithLogAsync(MSE_RPT_TEMPLATE mSE_RPT_TEMPLATE,
MSE_RPT_TEMPLATE_LOG mSE_RPT_TEMPLATE_LOG)
{
await _IDBInstance.DBOperation.InsertAsync(mSE_RPT_TEMPLATE);
await _IDBInstance.DBOperation.InsertAsync(mSE_RPT_TEMPLATE_LOG);
return true;
}
[UnitOfWork]
public async Task<bool> UpdateTepWithLogAsync(MSE_RPT_TEMPLATE mSE_RPT_TEMPLATE,
MSE_RPT_TEMPLATE_LOG mSE_RPT_TEMPLATE_LOG)
{
await _IDBInstance.DBOperation.UpdateAsync(mSE_RPT_TEMPLATE);
await _IDBInstance.DBOperation.InsertAsync(mSE_RPT_TEMPLATE_LOG);
return true;
}
#endregion
}
}
1、第一个代码块主要是为对需要事务的方法进行标注
2、第二个代码块主要是对事务进行控制的;
版权声明
本文为[驾驭人生]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq165285727/article/details/124343596
边栏推荐
- Learning go language 0x01: start from the official website
- Usage record of map < qstring, bool >
- oh-my-lotto
- 零钱兑换II——【LeetCode】
- Prevent SQL injection in web projects
- Database design of simple voting system
- Cognition and R & D technology of micro robot
- Explain in detail the pitfalls encountered in DTS due to the time zone problems of timestamp and datetime in MySQL
- GPU, CUDA,cuDNN三者的关系总结
- 解析幼儿教育中steam教育的融合
猜你喜欢
Design and practice of the smallest short website system in the whole network
On the integration of steam education in early childhood education
Yunna | how to manage the company's fixed assets and how to manage fixed assets
Redis学习之五---高并发分布式锁实战
Tensorflow使用keras创建神经网络的方法
qt 64位静态版本显示gif
年度最尴尬的社死瞬间,是Siri给的
qt5.8 64 位静态库中想使用sqlite但静态库没有编译支持库的方法
分享两个实用的shell脚本
docker MySQL主从备份
随机推荐
Write console script by laravel
MySQL8. 0 upgraded stepping on the pit Adventure
MySQL sorting feature details
小程序 支付
ImportError: libX11. so. 6: cannot open shared object file: No such file or directory
Solve the problem of "suncertpathbuilderexception: unable to find valid certification path to requested target"
IFLYTEK's revenue in 2021 was 18.3 billion yuan: a year-on-year increase of 41% and a net profit of 1.556 billion yuan
redis优化系列(二)Redis主从原理、主从常用配置
Using Baidu PaddlePaddle EasyDL to accomplish specified target recognition
Overall plan management mode in maker Education
Database design of forum system
让中小学生在快乐中学习的创客教育
When the activity is in progress! Click the link to join the live studio to participate in "can AI really save energy?" Let's have a discussion!
QT 64 bit static version display gif
Analyzing the role of social robots in basic science
探究机器人教育的器材与教学
配电房远程综合监控系统在10kV预制舱项目中的应用
MySQL failed to insert the datetime type field without single quotation marks
PDMS soft lithography process
My creation anniversary