AOP +FreeSql 跨方法异步事务

  • Autofac.Extensions.DependencyInjection
  • Autofac.Extras.DynamicProxy
  • Castle.Core.AsyncInterceptor(异步方法AOP拦截)

源码

csproj

        <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="6.0.0" />
<PackageReference Include="Autofac.Extras.DynamicProxy" Version="5.0.0" />
<PackageReference Include="Castle.Core.AsyncInterceptor" Version="1.7.0" />

使用Autofac实现特性标签,事务处理

创建一个标识事务的特性标签

[AttributeUsage(AttributeTargets.Method, Inherited = true)]
public class TransactionalAttribute : Attribute
{
/// <summary>
/// 事务传播方式
/// </summary>
public Propagation Propagation { get; set; } = Propagation.Required; /// <summary>
/// 事务隔离级别
/// </summary>
public IsolationLevel? IsolationLevel { get; set; }
}

Autofac

Program.CS 替换默认的DI CreateHostBuilder方法

 Host.CreateDefaultBuilder(args).UseServiceProviderFactory(new AutofacServiceProviderFactory())

Startup.cs配置服务

public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterModule(new AutofacModule());
}

这里给BlogService方法注入UnitOfWorkInterceptor拦截处理。直接注入类。

public class AutofacModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<UnitOfWorkInterceptor>();
builder.RegisterType<UnitOfWorkAsyncInterceptor>(); builder.RegisterType<BlogService>()
.InterceptedBy(typeof(UnitOfWorkInterceptor))
.EnableClassInterceptors(); }
    List<Type> interceptorServiceTypes = new List<Type>()
{
typeof(UnitOfWorkInterceptor)
};
//service所在dll
Assembly servicesDllFile = Assembly.Load("LinCms.Application"); builder.RegisterAssemblyTypes(servicesDllFile)
.Where(a => a.Name.EndsWith("Service"))
.AsImplementedInterfaces()
.InstancePerLifetimeScope()
.PropertiesAutowired()// 属性注入
.InterceptedBy(interceptorServiceTypes.ToArray())
.EnableInterfaceInterceptors();

AOP

    public class UnitOfWorkInterceptor : IInterceptor
{
private readonly UnitOfWorkAsyncInterceptor asyncInterceptor; public UnitOfWorkInterceptor(UnitOfWorkAsyncInterceptor interceptor)
{
asyncInterceptor = interceptor;
} public void Intercept(IInvocation invocation)
{
asyncInterceptor.ToInterceptor().Intercept(invocation);
}
} public class UnitOfWorkAsyncInterceptor : IAsyncInterceptor
{
private readonly UnitOfWorkManager _unitOfWorkManager;
private readonly ILogger<UnitOfWorkAsyncInterceptor> _logger;
IUnitOfWork _unitOfWork; public UnitOfWorkAsyncInterceptor(UnitOfWorkManager unitOfWorkManager, ILogger<UnitOfWorkAsyncInterceptor> logger)
{
_unitOfWorkManager = unitOfWorkManager;
_logger = logger;
} private bool TryBegin(IInvocation invocation)
{
//_unitOfWork = _unitOfWorkManager.Begin(Propagation.Requierd);
//return true;
var method = invocation.MethodInvocationTarget ?? invocation.Method;
var attribute = method.GetCustomAttributes(typeof(TransactionalAttribute), false).FirstOrDefault();
if (attribute is TransactionalAttribute transaction)
{
_unitOfWork = _unitOfWorkManager.Begin(transaction.Propagation, transaction.IsolationLevel);
return true;
} return false;
} /// <summary>
/// 拦截同步执行的方法
/// </summary>
/// <param name="invocation"></param>
public void InterceptSynchronous(IInvocation invocation)
{
if (TryBegin(invocation))
{
int? hashCode = _unitOfWork.GetHashCode();
try
{
invocation.Proceed();
_logger.LogInformation($"----- 拦截同步执行的方法-事务 {hashCode} 提交前----- ");
_unitOfWork.Commit();
_logger.LogInformation($"----- 拦截同步执行的方法-事务 {hashCode} 提交成功----- ");
}
catch
{
_logger.LogError($"----- 拦截同步执行的方法-事务 {hashCode} 提交失败----- ");
_unitOfWork.Rollback();
throw;
}
finally
{
_unitOfWork.Dispose();
}
}
else
{
invocation.Proceed();
}
} /// <summary>
/// 拦截返回结果为Task的方法
/// </summary>
/// <param name="invocation"></param>
public void InterceptAsynchronous(IInvocation invocation)
{
if (TryBegin(invocation))
{
invocation.ReturnValue = InternalInterceptAsynchronous(invocation);
}
else
{
invocation.Proceed();
}
} private async Task InternalInterceptAsynchronous(IInvocation invocation)
{
string methodName =
$"{invocation.MethodInvocationTarget.DeclaringType?.FullName}.{invocation.Method.Name}()";
int? hashCode = _unitOfWork.GetHashCode(); using (_logger.BeginScope("_unitOfWork:{hashCode}", hashCode))
{
_logger.LogInformation($"----- async Task 开始事务{hashCode} {methodName}----- "); invocation.Proceed(); try
{
await (Task)invocation.ReturnValue;
_unitOfWork.Commit();
_logger.LogInformation($"----- async Task 事务 {hashCode} Commit----- ");
}
catch (System.Exception)
{
_unitOfWork.Rollback();
_logger.LogError($"----- async Task 事务 {hashCode} Rollback----- ");
throw;
}
finally
{
_unitOfWork.Dispose();
}
} } /// <summary>
/// 拦截返回结果为Task<TResult>的方法
/// </summary>
/// <param name="invocation"></param>
/// <typeparam name="TResult"></typeparam>
public void InterceptAsynchronous<TResult>(IInvocation invocation)
{
invocation.ReturnValue = InternalInterceptAsynchronous<TResult>(invocation);
} private async Task<TResult> InternalInterceptAsynchronous<TResult>(IInvocation invocation)
{
TResult result;
if (TryBegin(invocation))
{
string methodName = $"{invocation.MethodInvocationTarget.DeclaringType?.FullName}.{invocation.Method.Name}()";
int hashCode = _unitOfWork.GetHashCode();
_logger.LogInformation($"----- async Task<TResult> 开始事务{hashCode} {methodName}----- "); try
{
invocation.Proceed();
result = await (Task<TResult>)invocation.ReturnValue;
_unitOfWork.Commit();
_logger.LogInformation($"----- async Task<TResult> Commit事务{hashCode}----- ");
}
catch (System.Exception)
{
_unitOfWork.Rollback();
_logger.LogError($"----- async Task<TResult> Rollback事务{hashCode}----- ");
throw;
}
finally
{
_unitOfWork.Dispose();
}
}
else
{
invocation.Proceed();
result = await (Task<TResult>)invocation.ReturnValue;
}
return result;
}
}

没有接口,必须使用virtual虚方法。

    public class BlogService
{
/// <summary>
/// 当出现异常时,不会插入数据
/// </summary>
/// <param name="createBlogDto"></param>
[Transactional]
public virtual void CreateBlogTransactional(CreateBlogDto createBlogDto)
{
Blog blog = _mapper.Map<Blog>(createBlogDto);
blog.CreateTime = DateTime.Now;
_blogRepository.Insert(blog); List<Tag> tags = new List<Tag>();
createBlogDto.Tags.ForEach(r =>
{
tags.Add(new Tag { TagName = r });
});
if (createBlogDto.Title == "abc")
{
throw new Exception("test exception");
}
_tagRepository.Insert(tags);
}
}

AOP +FreeSql 跨方法异步事务的更多相关文章

  1. Asp.netCore 3.1控制器属性注入and异步事务Aop by AutoFac

    Aspect Oriented Programming(AOP)是较为热门的一个话题.AOP,国内我们都习惯称之为:面向切面编程 下面直接code 干货展示:(一般人我还不告诉,嘻嘻) 1:导入相关的 ...

  2. 使用spring声明式事务,spring使用AOP来支持声明式事务,会根据事务属性,自动在方法调用之前决定是否开启一个事务,并在方法执行之后决定事务提交或回滚事务。

    使用spring声明式事务,spring使用AOP来支持声明式事务,会根据事务属性,自动在方法调用之前决定是否开启一个事务,并在方法执行之后决定事务提交或回滚事务.

  3. Spring.net 间接调用被AOP拦截的方法失效(无法进入aop的拦截方法)

    .下面的tx要定义 <objects xmlns="http://www.springframework.net" xmlns:db="http://www.spr ...

  4. spring声明式事务 同一类内方法调用事务失效

    只要避开Spring目前的AOP实现上的限制,要么都声明要事务,要么分开成两个类,要么直接在方法里使用编程式事务 [问题] Spring的声明式事务,我想就不用多介绍了吧,一句话“自从用了Spring ...

  5. (H5)FormData+AJAX+SpringMVC跨域异步上传文件

    最近都没时间整理资料了,一入职就要弄懂业务,整天被业务弄得血崩. 总结下今天弄了一个早上的跨域异步上传文件.主要用到技术有HTML5的FormData,AJAX,Spring MVC. 首先看下上传页 ...

  6. 【事务】<查询不到同一调用方法其它事务提交的更新>解决方案

    最近遇到一个很棘手的问题,至今也解释不清楚原因,不过已经找到了解决方案. 先来看看Propagation属性的值含义,@Transactional中Propagation属性有7个选项可供选择: Pr ...

  7. spring声明式事务 同一类内方法调用事务失效(转)

    原文 https://blog.csdn.net/jiesa/article/details/53438342 [问题] Spring的声明式事务,我想就不用多介绍了吧,一句话“自从用了Spring ...

  8. Spring开启方法异步执行

    @EnableAsync @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(Async ...

  9. Jquery~跨域异步上传文件

    先说明白 这个跨域异步上传功能我们借助了Jquery.form插件,它在异步表单方面很有成效,而跨域我们会在HTTP响应头上添加access-control-allow-method,当然这个头标记只 ...

随机推荐

  1. hdu4126Genghis Khan the Conqueror (最小生成树+树形dp)

    Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 327680/327680 K (Java/Others) Total Submiss ...

  2. Java-Swing的JFrame的一些插件使用详解

    JFrame介绍: 在 JFrame 对象中可以使用add方法添加 AWT 或者 Swing 组件. JFrame 有一个 Content Pane,窗口能显示的所有组件都是添加在这个 Content ...

  3. poj1821 Fence(dp,单调队列优化)

    题意: 由k(1 <= K <= 100)个工人组成的团队应油漆围墙,其中包含N(1 <= N <= 16 000)个从左到右从1到N编号的木板.每个工人i(1 <= i ...

  4. python实现通过指定浏览器免费观看vip视频

    程序是先通过一个解析视频的网站,然后我们提取其接口,然后实现观看vip视频的目的 所以说免费观看视频python程序很容易,但是下载视频就有些许麻烦了,下载视频请见我另一篇博客:python+fidd ...

  5. Codeforces Round #652 (Div. 2)D. TediousLee 推导

    题意: Rooted Dead Bush (RDB) of level 1是只有一个点,如下图 当(RDB) of level i变成(RDB) of level i+1的时候,每一个顶点要进行下面的 ...

  6. NCD 2019 H. Mr. Hamra and his quantum particles

    题意:给你n个数,有m次操作,每次使得两个数相连接,询问q次,问某两个数是否连接在一起. 题解:这其实是一道并查集的裸题,这里就不再多说了,写个路径压缩的find函数即可. 代码: #include ...

  7. 【转】K8S中部署Helm

    K8S中的包管理工具 1. 客户端Helm(即Helm)  通过脚本安装:curl https://raw.githubusercontent.com/helm/helm/master/scripts ...

  8. 数据分析常用库(numpy,pandas,matplotlib,scipy)

    概述 numpy numpy(numeric python)是 python 的一个开源数值计算库,主要用于数组和矩阵计算.底层是 C 语言,运行效率远高于纯 python 代码.numpy主要包含2 ...

  9. ARMv7-A 架构下的MMU

    ARM架构中MMU的作用主要就是将CPU发出的虚拟地址转换成为物理地址,从实现内核和用户程序和用户程序之间的虚拟地址空间隔离.MMU的主要组成为两部分,其一是内部的TLBs缓存:还有就是转换表装换单元 ...

  10. Watch the Wifi: Visually Stunning Look at the Digital World Invading Cities (video)

    http://singularityhub.com/2011/04/01/watch-the-wifi-visually-stunning-look-at-the-digital-world-inva ...