網站首頁 編程語言 正文
引言
在看.NET Core 源碼的管道模型中間件(Middleware)部分,覺得這個流程組裝,思路挺好的,于是就分享給大家。本次代碼實現就直接我之前寫的動態代理實現AOP的基礎上改的,就不另起爐灶了,主要思路就是運用委托。對委托不理解的可留言,我寫一篇委托的常規使用方式,以及底層原理(編譯器)的文章
沒看過上一章的,我這里大家給貼一下地址:.NET Core 實現動態代理做AOP(面向切面編程)
接下來進入正題
1.定義接口IInterceptor
定義好我們AOP需要實現的接口,不同職責可以定義不同接口,大家根據實際情況劃分
internal interface IInterceptor { } internal interface IInterceptorAction : IInterceptor { /// <summary> /// 執行之前 /// </summary> /// <param name="args">參數</param> void AfterAction(object?[]? args); /// <summary> /// 執行之后 /// </summary> /// <param name="args">參數</param> /// <param name="result">結果</param> void BeforeAction(object?[]? args, object? result); }
2.定義特性
這里只定義一個基類特性類,繼承標記接口,用于設置共通配置,且利于后面反射查找
[AttributeUsage(AttributeTargets.Class)] internal class BaseInterceptAttribute : Attribute, IInterceptor { }
3.編寫生成代理類的邏輯
只需要繼承.NET CORE 原生DispatchProxy類,重寫相關業務代碼
3.1 編寫創建代理方法
編寫一個我們自己的Create方法(),這兩個參數為了后面調用目標類儲備的,方法實現就只需要調用DispatchProxy類的Create()
internal class DynamicProxy<T> : DispatchProxy { public T Decorated { get; set; }//目標類 public IEnumerable<IInterceptorAction> Interceptors { get; set; } // AOP動作 /// <summary> /// 創建代理實例 /// </summary> /// <param name="decorated">代理的接口類型</param> /// <param name="afterAction">方法執行前執行的事件</param> /// <param name="beforeAction">方法執行后執行的事件</param> /// <returns></returns> public T Create(T decorated, IEnumerable<IInterceptor> interceptors) { object proxy = Create<T, DynamicProxy<T>>(); // 調用DispatchProxy 的Create 創建一個代理實例 DynamicProxy<T> proxyDecorator = (DynamicProxy<T>)proxy; proxyDecorator.Decorated = decorated; proxyDecorator.Interceptors = interceptors.Where(c=>c.GetType().GetInterface(typeof(IInterceptorAction).Name) == typeof(IInterceptorAction)).Select(c=>c as IInterceptorAction); return (T)proxy; }
3.2 重寫Invoke方法
這個就是需要實現我們自己的業務了,大家看注釋應該就能看懂個大概了,目前這里只處理了IInterceptorAction接口邏輯,比如異常、異步等等,自己可按需實現。而流程組裝的精髓就三步
1.不直接去執行targetMethod.Invoke(),而是把它放到委托里面。
2.定義AssembleAction()方法來組裝流程,方法里面也不執行方法,也是返回一個執行方法的委托。
3.循環事先在Create()方法存儲的特性實例,調用AssembleAction()方法組裝流程,這樣就達到俄羅斯套娃的效果了。
protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) { Exception exception = null;//由委托捕獲變量,用來存儲異常 Func<object?[]?, object?> action = (args) => { try { return targetMethod?.Invoke(Decorated, args); } catch (Exception ex)//捕獲異常,不影響AOP繼續執行 { exception = ex; } return null; }; //進行倒序,使其按照由外置內的流程執行 foreach (var c in Interceptors.Reverse()) { action = AssembleAction(action, c); } //執行組裝好的流程 var result = action?.Invoke(args); //如果方法有異常拋出異常 if (exception != null) { throw exception; } return result; } private Func<object?[]?, object?>? AssembleAction(Func<object?[]?, object?>? action, IInterceptorAction c) { return (args) => { //執行之前的動作 AfterAction(c.AfterAction, args); var result = action?.Invoke(args); //執行之后的動作 BeforeAction(c.BeforeAction, args, result); return result; }; } private void AfterAction(Action<object?[]?> action, object?[]? args) { try { action(args); } catch (Exception ex) { Console.WriteLine($"執行之前異常:{ex.Message},{ex.StackTrace}"); } } private void BeforeAction(Action<object?[]?, object?> action, object?[]? args, object? result) { try { action(args, result); } catch (Exception ex) { Console.WriteLine($"執行之后異常:{ex.Message},{ex.StackTrace}"); } } }
4.定義一個工廠
工廠用于專門來為我們創建代理類,邏輯很簡單,后續大家也可以按需編寫,目前邏輯就是利用反射獲取目標類的特性,把參數組裝起來。
internal class ProxyFactory { /// <summary> /// 創建代理實例 /// </summary> /// <param name="decorated">代理的接口類型</param> /// <returns></returns> public static T Create<T>() { var decorated = ServiceHelp.GetService<T>(); var type = decorated.GetType(); var interceptAttribut = type.GetCustomAttributes<BaseInterceptAttribute>(); //創建代理類 var proxy = new DynamicProxy<T>().Create(decorated, interceptAttribut); return proxy; } }
5.定義ServiceHelp
這個是為了使得我們全局只用一個作用域的IOC容器
public static class ServiceHelp { public static IServiceProvider? serviceProvider { get; set; } public static void BuildServiceProvider(IServiceCollection serviceCollection) { //構建容器 serviceProvider = serviceCollection.BuildServiceProvider(); } public static T GetService<T>(Type serviceType) { return (T)serviceProvider.GetService(serviceType); } public static T GetService<T>() { return serviceProvider.GetService<T>(); } }
6.測試
6.1 編程AOP實現
寫兩個特性實現,繼承基類特性,實現Action接口邏輯,測試兩個特性隨意調換位置進行組裝流程
internal class AOPTest1Attribut : BaseInterceptAttribute, IInterceptorAction { public void AfterAction(object?[]? args) { Console.WriteLine($"AOP1方法執行之前,args:{args[0] + "," + args[1]}"); // throw new Exception("異常測試(異常,但依然不能影響程序執行)"); } public void BeforeAction(object?[]? args, object? result) { Console.WriteLine($"AOP1方法執行之后,result:{result}"); } } internal class AOPTest2Attribut : BaseInterceptAttribute, IInterceptorAction { public void AfterAction(object?[]? args) { Console.WriteLine($"AOP2方法執行之前,args:{args[0] + "," + args[1]}"); } public void BeforeAction(object?[]? args, object? result) { Console.WriteLine($"AOP2方法執行之后,result:{result}"); } }
6.2 編寫測試服務
寫一個簡單的測試服務,就比如兩個整數相加,然后標記上我們寫的AOP特性
internal interface ITestService { public int Add(int a, int b); } [AOPTest2Attribut] [AOPTest1Attribut] internal class TestService : ITestService { public int Add(int a, int b) { Console.WriteLine($"正在執行--》Add({a},{b})"); //throw new Exception("方法執行--》測試異常"); return a + b; } }
6.3 調用
1.把服務注冊到IOC
2.調用創建代理類的工廠
3.調用測試服務函數:.Add(1, 2)
IServiceCollection serviceCollection = new ServiceCollection(); serviceCollection.AddTransient<ITestService, TestService>(); ServiceHelp.BuildServiceProvider(serviceCollection); //用工廠獲取代理實例 var s = ProxyFactory.Create<ITestService>(); var sum = s.Add(1, 2);
6.4 效果圖
AOP1->AOP2->Add(a,b)
AOP2->AOP1->Add(a,b)
代碼上傳至gitee,AOP流程組裝分支:https://gitee.com/luoxiangbao/dynamic-proxy.git
原文鏈接:https://www.cnblogs.com/Bob-luo/archive/2022/01/11/15775999.html
相關推薦
- 2022-10-31 解決Python3中二叉樹前序遍歷的迭代問題_python
- 2024-01-07 IDEA中自動導包及快捷鍵
- 2023-04-13 next 配置全局scss變量、函數
- 2022-11-05 安裝ingress-nginx遇到的一些坑實戰記錄_云其它
- 2023-06-18 C#零基礎開發中最重要的概念總結_C#教程
- 2022-11-09 ORACLE中常用的幾種正則表達式小結_oracle
- 2023-08-30 linux服務器使用rsync 和 inotify或者sersync 實現服務器之間文件實時同步
- 2023-07-22 深入解讀springboot使用注解@value注入static變量
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支