.NET Core 利用委託進行動態流程組裝
引言
在看.NET Core 源碼的管道模型中間件(Middleware)部分,覺得這個流程組裝,思路挺好的,於是就分享給大家。本次程式碼實現就直接我之前寫的動態代理實現AOP的基礎上直接改了,就不另起爐灶了,主要思路就是運用委託。對委託不理解的可留言,我寫一篇委託的常規使用方式,以及底層原理(編譯器)的文章
沒看過上一章的,我這裡大家給貼一下地址:.NET Core 實現動態代理做AOP(面向切面編程) – 極客Bob – 部落格園 (cnblogs.com)
接下來進入正題
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 編寫測試服務
寫一個簡單的測試服務,就比如兩個整數相加
查看程式碼
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.2編程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.3 調用
1.把服務註冊到IOC
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流程組裝分支://gitee.com/luoxiangbao/dynamic-proxy.git