Autofac实现拦截器和切面编程

2023-11-05 19:58

本文主要是介绍Autofac实现拦截器和切面编程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Autofac.Annotation框架是我用.netcore写的一个注解式DI框架,基于Autofac参考 Spring注解方式所有容器的注册和装配,切面,拦截器等都是依赖标签来完成。

开源地址:https://github.com/yuzd/Autofac.Annotation

上期说了Autofac实现有条件的DI

本期讲的是最新重构的功能,这个功能也是赋予了这个框架的无限可能,也是我觉得设计的比较好的地方, 今天来说说我是怎么设计的。本篇文章我写的时候想了很久如何脱离代码去讲的很清楚,但是发现很难,因为设计的巧妙之处还是在于代码,得细品。至少我觉得比Spring的拦截器链用的代码少而精巧,而且更容器理解(手动狗头)

d4e16c8d252cd2348db03dbde4088de8.png

切面和拦截器介绍

拦截器是什么?

可以帮助我们方便在执行目标方法的

  • 前(Before)

  • 后(After)

  • 返回值时(AfterReturn)

  • 抛错误时(AfterThrowing)

  • 环绕(Around)

简单示例:

//自己实现一个拦截器public class TestHelloBefore:AspectBefore{public override Task Before(AspectContext aspectContext){Console.WriteLine("TestHelloBefore");return Task.CompletedTask;}}[Component]public class TestHello{[TestHelloBefore]//打上拦截器public virtual void Say(){Console.WriteLine("Say");}}

先执行 TestHelloBefor的Before方法再执行你的Say方法

更多使用示例请查看 Aspect拦截器

切面是什么?

定义一个切面(根据筛选器去实现满足条件的多个类的多个方法的“拦截器”

简单示例:

[Component]public class ProductController{public virtual string GetProduct(string productId){return "GetProduct:" + productId;}public virtual string UpdateProduct(string productId){return "UpdateProduct:" + productId;}}[Component]public class UserController{public virtual string GetUser(string userId){return "GetUser:" + userId;}public virtual string DeleteUser(string userId){return "DeleteUser:" + userId;}}// *Controller 代表匹配 只要是Controller结尾的类都能匹配// Get* 代表上面匹配成功的类下 所以是Get打头的方法都能匹配[Pointcut(Class = "*Controller",Method = "Get*")]public class LoggerPointCut{[Around]public async Task Around(AspectContext context,AspectDelegate next){Console.WriteLine("PointcutTest1.Around-start");await next(context);Console.WriteLine("PointcutTest1.Around-end");}[Before]public void Before(){Console.WriteLine("PointcutTest1.Before");}[After]public void After(){Console.WriteLine("PointcutTest1.After");}[AfterReturn(Returing = "value1")]public void AfterReturn(object value1){Console.WriteLine("PointcutTest1.AfterReturn");}[AfterThrows(Throwing = "ex1")]public void Throwing(Exception ex1){Console.WriteLine("PointcutTest1.Throwing");}       }

更多示例请查看 Pointcut切面编程

如何实现的

分为3步

  • 1.搜集拦截算子(比如Before/After等这个我们叫算子)

  • 2.构造拦截器链(按照上面图的方式把算子链接起来)

  • 3.生成代理类代理目标方法去执行上面构造的拦截器链

1.搜集拦截算子

因为拦截器的使用是约定了要继承 AspectInvokeAttribute

/// <summary>///     AOP拦截器 默认包含继承关系/// </summary>[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]public class AspectInvokeAttribute : Attribute{/// <summary>///     排序 值越低,优先级越高/// </summary>public int OrderIndex { get; set; }/// <summary>///     分组名称/// </summary>public string GroupName { get; set; }}
cb1e9daf12fb8dcc705259fb509135f8.png
image

这一组注解是暴露给外部使用,来搜集哪些类的哪些方法需要增强

接下来需要去针对性去实现每一种增强器要做的事情

定义一个增强器接口IAdvice

internal interface IAdvice{/// <summary>///  拦截器方法/// </summary>/// <param name="aspectContext">执行上下文</param>/// <param name="next">下一个增强器</param>/// <returns></returns>Task OnInvocation(AspectContext aspectContext, AspectDelegate next);}
18e6f5218f31a85e20651a65e75b8455.png
image
Before增强器
/// <summary>/// 前置增强器/// </summary>internal class AspectBeforeInterceptor : IAdvice{private readonly AspectBefore _beforeAttribute;public AspectBeforeInterceptor(AspectBefore beforeAttribute){_beforeAttribute = beforeAttribute;}public async Task OnInvocation(AspectContext aspectContext, AspectDelegate next){//先执行Before逻辑await this._beforeAttribute.Before(aspectContext);//在走下一个增强器await next.Invoke(aspectContext);}}
After增强器
/// <summary>/// 后置增强器/// </summary>internal class AspectAfterInterceptor : IAdvice{private readonly AspectAfter _afterAttribute;private readonly bool _isAfterAround;public AspectAfterInterceptor(AspectAfter afterAttribute, bool isAfterAround = false){_afterAttribute = afterAttribute;_isAfterAround = isAfterAround;}public async Task OnInvocation(AspectContext aspectContext, AspectDelegate next){try{if (!_isAfterAround) await next.Invoke(aspectContext);}finally{//不管成功还是失败都会执行的 await this._afterAttribute.After(aspectContext, aspectContext.Exception ?? aspectContext.ReturnValue);}}}
环绕增强器
/// <summary>/// 环绕返回拦截处理器/// </summary>internal class AspectAroundInterceptor : IAdvice{private readonly AspectArround _aroundAttribute;private readonly AspectAfterInterceptor _aspectAfter;private readonly AspectAfterThrowsInterceptor _aspectThrows;public AspectAroundInterceptor(AspectArround aroundAttribute, AspectAfter aspectAfter, AspectAfterThrows chainAspectAfterThrows){_aroundAttribute = aroundAttribute;if (aspectAfter != null){_aspectAfter = new AspectAfterInterceptor(aspectAfter, true);}if (chainAspectAfterThrows != null){_aspectThrows = new AspectAfterThrowsInterceptor(chainAspectAfterThrows, true);}}public async Task OnInvocation(AspectContext aspectContext, AspectDelegate next){Exception exception = null;try{if (_aroundAttribute != null){await _aroundAttribute.OnInvocation(aspectContext, next);return;}}catch (Exception ex){exception = ex;}finally{if (exception == null && _aspectAfter != null) await _aspectAfter.OnInvocation(aspectContext, next);}try{if (exception != null && _aspectAfter != null){await _aspectAfter.OnInvocation(aspectContext, next);}if (exception != null && _aspectThrows != null){await _aspectThrows.OnInvocation(aspectContext, next);}}finally{if (exception != null) throw exception;}}}
返回值增强器
/// <summary>/// 后置返值增强器/// </summary>internal class AspectAfterReturnInterceptor : IAdvice{private readonly AspectAfterReturn _afterAttribute;public AspectAfterReturnInterceptor(AspectAfterReturn afterAttribute){_afterAttribute = afterAttribute;}public async Task OnInvocation(AspectContext aspectContext, AspectDelegate next){await next.Invoke(aspectContext);//执行异常了不执行after 去执行Throwif (aspectContext.Exception != null){return;}if (_afterAttribute != null){await this._afterAttribute.AfterReturn(aspectContext, aspectContext.ReturnValue);}}}
异常返回增强器
/// <summary>/// 异常返回增强器/// </summary>internal class AspectAfterThrowsInterceptor : IAdvice{private readonly AspectAfterThrows _aspectThrowing;private readonly bool _isFromAround;public AspectAfterThrowsInterceptor(AspectAfterThrows throwAttribute, bool isFromAround = false){_aspectThrowing = throwAttribute;_isFromAround = isFromAround;}public async Task OnInvocation(AspectContext aspectContext, AspectDelegate next){try{if (!_isFromAround) await next.Invoke(aspectContext);}finally{//只有目标方法出现异常才会走 增强的方法出异常不要走if (aspectContext.Exception != null){Exception ex = aspectContext.Exception;if (aspectContext.Exception is TargetInvocationException targetInvocationException){ex = targetInvocationException.InnerException;}if (ex == null){ex = aspectContext.Exception;}var currentExType = ex.GetType();if (_aspectThrowing.ExceptionType == null || _aspectThrowing.ExceptionType == currentExType){await _aspectThrowing.AfterThrows(aspectContext, aspectContext.Exception);}}}}}
2. 组装增强器们成为一个调用链
9ecac031c6228e01ca9fdc92672ea5e1.png
image

每一个node的有三个信息,如下

/// <summary>/// 拦截node组装/// </summary>internal class AspectMiddlewareComponentNode{/// <summary>/// 下一个/// </summary>public AspectDelegate Next;/// <summary>/// 执行器/// </summary>public AspectDelegate Process;/// <summary>/// 组件/// </summary>public Func<AspectDelegate, AspectDelegate> Component;}

采用LinkedList来构建我们的拉链式调用, 我们把上面的每个增强器作为一个个middeware,添加进来。

internal class AspectMiddlewareBuilder{private readonly LinkedList<AspectMiddlewareComponentNode> Components = new LinkedList<AspectMiddlewareComponentNode>();/// <summary>/// 新增拦截器链/// </summary>/// <param name="component"></param>public void Use(Func<AspectDelegate, AspectDelegate> component){var node = new AspectMiddlewareComponentNode{Component = component};Components.AddLast(node);}/// <summary>/// 构建拦截器链/// </summary>/// <returns></returns>public AspectDelegate Build(){var node = Components.Last;while (node != null){node.Value.Next = GetNextFunc(node);node.Value.Process = node.Value.Component(node.Value.Next);node = node.Previous;}return Components.First.Value.Process;}/// <summary>/// 获取下一个/// </summary>/// <param name="node"></param>/// <returns></returns>private AspectDelegate GetNextFunc(LinkedListNode<AspectMiddlewareComponentNode> node){return node.Next == null ? ctx => Task.CompletedTask : node.Next.Value.Process;}}

然后build方法会构建成一个一层嵌套一层的pipeline管道(一个委托)

765bdaa9485d634e7e2e6b5cdd9b0992.png
image

更多关于这种设计模式更多信息请参考我另外一篇文章:中间件(middlewware)模式

构建的顺序: After, Around,Before,最后才是实际的方法

这里尤其要注意需要将AfterReturn 和 AfterThrowing在Around增强器里面调用,这里要细品!

按照我们的需求构建的完整执行示意图如下:

单个拦截器或者切面
45b716210c2b0c677b692a010b50df67.png
image
多个拦截器或者切面
2cee762f6b40530582ceb9c61a23b931.png
image

3.生成代理类代理目标方法去执行上面构造的拦截器链

这一步就简单了,如果检测到目标有打拦截器注解,则会给这个类动态创建一个proxy类,

生成代理类用的是castle.core的dynamic组件

默认的是Class+virtual的方式对目标方法进行拦截

88c42bfcbfee9b6cc01294fa5cd2eeeb.png
image

注意:考虑到性能,在项目启动的时候把构建好进行缓存,然后再拦截器里面使用

https://github.com/yuzd/Autofac.Annotation/wiki


我是正东,学的越多不知道也越多。热爱可低漫长岁月,这一刻我很爽!

这篇关于Autofac实现拦截器和切面编程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/352139

相关文章

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

golang版本升级如何实现

《golang版本升级如何实现》:本文主要介绍golang版本升级如何实现问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录golanwww.chinasem.cng版本升级linux上golang版本升级删除golang旧版本安装golang最新版本总结gola

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Mysql实现范围分区表(新增、删除、重组、查看)

《Mysql实现范围分区表(新增、删除、重组、查看)》MySQL分区表的四种类型(范围、哈希、列表、键值),主要介绍了范围分区的创建、查询、添加、删除及重组织操作,具有一定的参考价值,感兴趣的可以了解... 目录一、mysql分区表分类二、范围分区(Range Partitioning1、新建分区表:2、分

MySQL 定时新增分区的实现示例

《MySQL定时新增分区的实现示例》本文主要介绍了通过存储过程和定时任务实现MySQL分区的自动创建,解决大数据量下手动维护的繁琐问题,具有一定的参考价值,感兴趣的可以了解一下... mysql创建好分区之后,有时候会需要自动创建分区。比如,一些表数据量非常大,有些数据是热点数据,按照日期分区MululbU

MySQL中查找重复值的实现

《MySQL中查找重复值的实现》查找重复值是一项常见需求,比如在数据清理、数据分析、数据质量检查等场景下,我们常常需要找出表中某列或多列的重复值,具有一定的参考价值,感兴趣的可以了解一下... 目录技术背景实现步骤方法一:使用GROUP BY和HAVING子句方法二:仅返回重复值方法三:返回完整记录方法四:

IDEA中新建/切换Git分支的实现步骤

《IDEA中新建/切换Git分支的实现步骤》本文主要介绍了IDEA中新建/切换Git分支的实现步骤,通过菜单创建新分支并选择是否切换,创建后在Git详情或右键Checkout中切换分支,感兴趣的可以了... 前提:项目已被Git托管1、点击上方栏Git->NewBrancjsh...2、输入新的分支的

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方