当前位置:网站首页>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
{
}
边栏推荐
猜你喜欢
win10 配置tensorflow(GPU) anaconda3 cuda9.0 cudnn for 9.0
梅科尔工作室-DjangoWeb 应用框架+MySQL数据库第三次培训
目标检测——Faster R-CNN 之 Fast R-CNN
TAMNet:A loss-balanced multi-task model for simultaneous detection and segmentation
CVPR2020:Seeing Through Fog Without Seeing Fog
解决jupyter中import torch出错问题
AIDL 简介以及使用
LiDAR Snowfall Simulation for Robust 3D Object Detection
CMT2380F32模块开发2-IDE软件配置
从概念认识AI
随机推荐
CVPR2022——A VERSATILE MULTI-VIEW FRAMEWORK
目标检测思维导图
智慧工地 安全帽识别系统
安全帽识别-施工安全的“监管者”
CMT2380F32模块开发10-高级定时器例程
Hard hat recognition algorithm
win10 配置tensorflow(GPU) anaconda3 cuda9.0 cudnn for 9.0
防盗链——防止其他页面通过url直接访问本站资源
珍爱网App竞品分析报告
TAMNet:A loss-balanced multi-task model for simultaneous detection and segmentation
Toward a Unified Model
Pay “Attention” to Adverse Weather
Toolbar 和 DrawerLayout 滑动菜单
CMT2380F32模块开发7-reset例程
Use regex to verify whether the file name is legal
咕咚vs悦跑圈的竞品分析
通过字符设备虚拟文件系统实现kernel和userspace数据交换(基于kernel 5.8测试通过)
如何快速转行做产品经理
梅科尔工作室-HarmonyOS应用开发的第二次培训
Zhejiang University School of Software 2020 Guarantee Research Computer Real Question Practice