ASP.NET CORE 通过特性封装事务

在 .NET Core 中,可以使用自定义的 ActionFilter 来封装事务。

1.创建全局事务

  public class TransactionFilter : IActionFilter
   {
         
        ISqlSugarClient _db;//你也可以换EF CORE对象 或者ADO对象都行
        public TransactionFilter(ISqlSugarClient db)//(ISqlSugarClient)需要IOC注入处理事务的对象
        { 
            _db=db;
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
             _db.AsTenant().BeginTran();//接口要加.AsTenant()
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Exception == null)
            {
                _db.AsTenant().CommitTran();
            }
            else
            {
                _db.AsTenant().RollBack();
            }
        }
    }

2.IOC注册

//注入事务对象
builder.Services.AddScoped<TransactionFilter>();

//注入ORM对象
//注册上下文:AOP里面可以获取IOC对象,如果有现成框架比如Furion可以不写这一行
services.AddHttpContextAccessor();
//注册SqlSugar
services.AddSingleton<ISqlSugarClient>(s =>
{
    SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
    {
        DbType = SqlSugar.DbType.Sqlite,
        ConnectionString = "DataSource=sqlsugar-dev.db",
        IsAutoCloseConnection = true,
    },
   db =>
   {
       //单例参数配置,所有上下文生效
       db.Aop.OnLogExecuting = (sql, pars) =>
       {
           //获取作IOC作用域对象
           //var appServive = s.GetService<IHttpContextAccessor>();
           //var obj = appServive?.HttpContext?.RequestServices.GetService<Log>();
           //Console.WriteLine("AOP" + obj.GetHashCode());
       };
   });
    return sqlSugar;
});

3.在接口打上事务

 [ServiceFilter(typeof(TransactionFilter))]//加上这行就可以用了
 [HttpGet(Name = "GetWeatherForecast")]
 public IEnumerable<WeatherForecast> Get()
 {
        .....数据库操作...     
 }

 

果糖网