当前位置:网站首页>net6 的Web MVC项目中事务功能的应用
net6 的Web MVC项目中事务功能的应用
2022-08-11 05:24:00 【Three Big Stones】
主要原理是借助于ActionFilter过滤器对Action方法实现拦截,再加上TransactionScope事务处理功能,实现Action方法的事务功能。
1、实现IAsyncActionFilter接口,定义事务拦截器。
public class TransactionScopeFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
bool hasNotTransactionalAttribute = false;//action上是否标识不启用事务功能
if (context.ActionDescriptor is ControllerActionDescriptor)
{
var actionDesc = (ControllerActionDescriptor)context.ActionDescriptor;
hasNotTransactionalAttribute = actionDesc.MethodInfo.IsDefined(typeof(NotTransactionalAttribute), false);
}
if (hasNotTransactionalAttribute)
{
await next();
return;
}
using var txScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
var result = await next();
if (result.Exception == null)//action执行结果没有异常则提交事务
{
txScope.Complete();
}
}
}
2、注册拦截器。
需要在Startup.cs代码中注册我们自定义的拦截器。
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMvcCore(opt => {
opt.Filters.Add<RateLimitFilter>();//添加限流支持
opt.Filters.Add<TransactionScopeFilter>();//添加事务支持
opt.Filters.Add<ExceptionFilter>();//添加异常处理支持
opt.Filters.Add<LogFilter>();
});
services.AddDbContext<BookDbContext>(opt=> {
var connectString = this.Configuration.GetSection("DbConnectionStr").Value;
opt.UseSqlServer(connectString);
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication1", Version = "v1" });
});
services.AddMemoryCache();//添加缓存服务
}
这样我们的action方法默认全部是支持事务功能的,如果不希望action添加事务支持,只需要在action方法上增加特性NotTransactional就可以了,这个是我自定义的一个标记特性。
public class NotTransactionalAttribute:Attribute
{
}
边栏推荐
猜你喜欢
Zhejiang University School of Software 2020 Guarantee Research Computer Real Question Practice
【调试记录1】提高MC3172浮点运算能力,IQmath库的获取与导入使用教程
Safety helmet recognition system
CMT2380F32模块开发2-IDE软件配置
跳转到微信小程序方法
梅科尔工作室-DjangoWeb 应用框架+MySQL数据库第五次培训
安全帽识别系统-解决监管难题
浙江大学软件学院2020年保研上机真题练习
CMT2380F32模块开发10-高级定时器例程
2022年最新安全帽佩戴识别系统
随机推荐
mAPH - Waymo dataset
Hard hat recognition algorithm
pip安装报错:is not a supported wheel on this platform
我心仪的数据集—目标检测为主
安全帽识别
Severe Weather 3D Object Detection Dataset Collection
AI智能图像识别的工作原理及行业应用
Maykel Studio - Django Web Application Framework + MySQL Database Third Training
自定义形状seekbar学习
CMT2380F32模块开发9-可编程计数阵列 PCA例程
CMT2380F32模块开发5-CLK例程
HTTP缓存机制详解
智慧工地 安全帽识别系统
Diagnostic Log and Trace——dlt的编译和安装
LAGRANGIAN FLUID SIMULATION WITH CONTINUOUS CONVOLUTIONS
微信和抖音都到十亿级用户了,作为产品经理的你们觉得哪个产品更成功?
Joint 3D Instance Segmentation and Object Detection for Autonomous Driving
关于mmdetection框架实用小工具说明
Toolbar 和 DrawerLayout 滑动菜单
Maykle Studio - Second Training in HarmonyOS App Development