您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關NetCore中怎么利用Transitional自定義注解事物,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
之前實現了NetCore實現自定義IOC容器注入,在Controller使用事物的過程中思考是否能夠像Spring一樣通過自定義注解實現事物管理,思路圖如下
事物的動作拆分只需要根據當前執行線程劃分Connection對象并開啟事物即可,重點是在Emit代碼織入過程中對異常捕捉的處理
處理過程中主要會用到BeginExceptionBlock開啟try代碼塊,BeginCatchBlock開啟catch代碼塊,EndExceptionBlock結束異常捕捉代碼塊
創建事物注解Transitional用來標記Controller中需要事物執行的方法
[AttributeUsage(AttributeTargets.Method)] public class Transitional : System.Attribute { public bool AutoRollBack { set; get; } public Transitional() { AutoRollBack = true; } }
Emit編織時需要注意異常捕捉時有返回值時建立全局變量返回,執行事物管理器類的靜態方法直接使用call,例如 ilOfMethod.Emit(OpCodes.Call, typeof(TransitionManage).GetMethod("DoRollBack")),同時Controller被攔截的方法需要標記Transitional注解且同時是虛方法
被代理類示例
public class TransitionalMovie{ [Transitional]public virtual void Test1(){ Console.WriteLine("Test1"); } [Transitional]public virtual string Test2(){ Console.WriteLine("Test2");throw new Exception("111");return "Hello"; } [Transitional(AutoRollBack = false)]public virtual void Test3(string Key){ Console.WriteLine("Test3"); Console.WriteLine(Key); }
IOC使用示例,IOC容器原理可參考c#通過Emit方式實現動態代理
var container = new ContainerBuilder(); container.RegisterType<TransitionalMovie>().EnableIntercept(); container.Build(); TransitionalMovie tm = container.Resolve<TransitionalMovie>(); tm.Test1(); string result = tm.Test2(); Console.WriteLine(result); tm.Test3("世界第一等");
動態代理生成類反編譯代碼
動態代理包含異常攔截與事物的全部代碼
public static Object CreateProxyObject(Type InterfaceType, Type ImpType, Type InterceptType, bool inheritMode = true, bool isInterceptAllMethod = true){string nameOfAssembly = ImpType.Name + "ProxyAssembly";string nameOfModule = ImpType.Name + "ProxyModule";string nameOfType = ImpType.Name + "Proxy";var assemblyName = new AssemblyName(nameOfAssembly); ModuleBuilder moduleBuilder = null;var assembly = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); moduleBuilder = assembly.DefineDynamicModule(nameOfModule); TypeBuilder typeBuilder;if (inheritMode) { typeBuilder = moduleBuilder.DefineType( nameOfType, TypeAttributes.Public, ImpType); }else{ typeBuilder = moduleBuilder.DefineType( nameOfType, TypeAttributes.Public, null, new[] { InterfaceType }); } InjectInterceptor(typeBuilder, ImpType, InterceptType, inheritMode, isInterceptAllMethod);var t = typeBuilder.CreateType();return Activator.CreateInstance(t); }private static void InjectInterceptor(TypeBuilder typeBuilder, Type ImpType, Type InterceptType, bool inheritMode, bool isInterceptAllMethod){#region 變量定義// ---- 變量定義 ----var constructorBuilder = typeBuilder.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, null);var ilOfCtor = constructorBuilder.GetILGenerator();//---- 攔截類對象定義 ----if (InterceptType == null) { InterceptType = typeof(DefaultIntercept); }//聲明var fieldInterceptor = typeBuilder.DefineField( "_interceptor", InterceptType, FieldAttributes.Private);//賦值ilOfCtor.Emit(OpCodes.Ldarg_0); ilOfCtor.Emit(OpCodes.Newobj, InterceptType.GetConstructor(new Type[0])); ilOfCtor.Emit(OpCodes.Stfld, fieldInterceptor);#endregion#region 代理對象定義//---- 實現類對象定義 ----//聲明var fieldBeProxy = typeBuilder.DefineField( "_beproxy", ImpType, FieldAttributes.Private);//賦值ilOfCtor.Emit(OpCodes.Ldarg_0); ilOfCtor.Emit(OpCodes.Newobj, ImpType.GetConstructor(new Type[0])); ilOfCtor.Emit(OpCodes.Stfld, fieldBeProxy); ilOfCtor.Emit(OpCodes.Ret);#endregion// ---- 定義類中的方法 ----var methodsOfType = ImpType.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(a => a.IsVirtual).ToArray();string[] ignoreMethodName = new[] { "GetType", "ToString", "GetHashCode", "Equals" };for (var i = 0; i < methodsOfType.Length; i++) {#region 方法是否需要攔截判斷,Object內置方法過濾bool IsMethodIntercept = false;bool IsTransitinal = false;var method = methodsOfType[i];//---- 過濾Object基類方法,如果是繼承,基類中的屬性get,set方法也要過濾 ----if (ignoreMethodName.Contains(method.Name) || method.Name.StartsWith("set_") || method.Name.StartsWith("get_")) {continue; }// ---- 判斷方法是否需要攔截 ----if (isInterceptAllMethod) {if (method.GetCustomAttribute(typeof(IgnoreInterceptAttibute)) == null) { IsMethodIntercept = true; } }else{if (method.GetCustomAttribute(typeof(InterceptAttibute)) != null) { IsMethodIntercept = true; } }// ---- 判斷方法是否需要納入事物管理中 ----if (method.GetCustomAttribute(typeof(Transitional)) != null) { IsTransitinal = true; }#endregion#region 泛型方法處理var methodParameterTypes = method.GetParameters().Select(p => p.ParameterType).ToArray();// ---- 定義方法名與參數 ----var methodBuilder = typeBuilder.DefineMethod( method.Name, MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.Standard, method.ReturnType, methodParameterTypes);//如果是泛型方法if (method.IsGenericMethod) {//獲取所有泛型參數類型定義Type[] Args = method.GetGenericArguments(); List<string> GenericArgNames = new List<string>();for (int j = 0; j < Args.Length; j++) { GenericArgNames.Add(Args[j].Name); }//代理類方法生成泛型參數定義GenericTypeParameterBuilder[] DGP = methodBuilder.DefineGenericParameters(GenericArgNames.ToArray());//泛型參數約束設置for (int j = 0; j < DGP.Length; j++) {//泛型參數繼承約束DGP[j].SetBaseTypeConstraint(Args[j].BaseType);//泛型參數完成接口約束DGP[j].SetInterfaceConstraints(Args[j].GetInterfaces()); } }#endregionvar ilOfMethod = methodBuilder.GetILGenerator();var methodresult = ilOfMethod.DeclareLocal(typeof(object)); //instance of result//賦值方法結果對象初始值為nullilOfMethod.Emit(OpCodes.Ldnull); ilOfMethod.Emit(OpCodes.Stloc_0);#region 事物攔截開始if (IsTransitinal) {//開始try模塊ilOfMethod.BeginExceptionBlock();//調用TransitionManage.StartTransitionilOfMethod.Emit(OpCodes.Call, typeof(TransitionManage).GetMethod("StartTransition")); ilOfMethod.Emit(OpCodes.Ldarg_0); }#endregion#region before攔截// ---- before ----if (IsMethodIntercept) {var parameters = ilOfMethod.DeclareLocal(typeof(object[])); ilOfMethod.Emit(OpCodes.Ldc_I4, methodParameterTypes.Length); ilOfMethod.Emit(OpCodes.Newarr, typeof(object)); ilOfMethod.Emit(OpCodes.Stloc, parameters);for (var j = 0; j < methodParameterTypes.Length; j++) { ilOfMethod.Emit(OpCodes.Ldloc, parameters); ilOfMethod.Emit(OpCodes.Ldc_I4, j); ilOfMethod.Emit(OpCodes.Ldarg, j + 1); ilOfMethod.Emit(OpCodes.Stelem_Ref); } ilOfMethod.Emit(OpCodes.Ldarg_0); ilOfMethod.Emit(OpCodes.Ldfld, fieldInterceptor);//攔截方法參數賦值if (inheritMode) {//繼承傳遞代理類本身ilOfMethod.Emit(OpCodes.Ldarg_0); }else{//接口傳遞實現類ilOfMethod.Emit(OpCodes.Ldarg_0); ilOfMethod.Emit(OpCodes.Ldfld, fieldBeProxy); } ilOfMethod.Emit(OpCodes.Ldstr, method.Name); ilOfMethod.Emit(OpCodes.Ldloc, parameters);//調用攔截類中的Before方法ilOfMethod.Emit(OpCodes.Callvirt, InterceptType.GetMethod("Before")); }#endregion#region 方法執行// ---- call ----////定義實現類局部變量//var localimpobj = ilOfMethod.DeclareLocal(ImpType);////new一個實現類的對象//ilOfMethod.Emit(OpCodes.Newobj, ImpType.GetConstructor(new Type[0]));////局部變量賦值//ilOfMethod.Emit(OpCodes.Stloc, localimpobj);////局部變量出棧,等待調用//ilOfMethod.Emit(OpCodes.Ldloc, localimpobj);//方法執行開始時間var localstart = ilOfMethod.DeclareLocal(typeof(DateTime)); ilOfMethod.Emit(OpCodes.Call, typeof(DateTime).GetMethod("get_Now")); ilOfMethod.Emit(OpCodes.Stloc, localstart);if (inheritMode) {//繼承方法調用父類的方法ilOfMethod.Emit(OpCodes.Ldarg_0);for (var j = 0; j < methodParameterTypes.Length; j++) { ilOfMethod.Emit(OpCodes.Ldarg, j + 1); } ilOfMethod.Emit(OpCodes.Call, ImpType.GetMethod(method.Name)); }else{//接口方法調用實現類的方法ilOfMethod.Emit(OpCodes.Ldarg_0); ilOfMethod.Emit(OpCodes.Ldfld, fieldBeProxy);for (var j = 0; j < methodParameterTypes.Length; j++) { ilOfMethod.Emit(OpCodes.Ldarg, j + 1); }//調用方法ilOfMethod.Emit(OpCodes.Callvirt, ImpType.GetMethod(method.Name)); }var localend = ilOfMethod.DeclareLocal(typeof(DateTime)); ilOfMethod.Emit(OpCodes.Call, typeof(DateTime).GetMethod("get_Now")); ilOfMethod.Emit(OpCodes.Stloc, localend);#endregion#region after攔截// ---- after ----if (IsMethodIntercept) {if (method.ReturnType == typeof(void)) { ilOfMethod.Emit(OpCodes.Ldnull); }else{ ilOfMethod.Emit(OpCodes.Box, method.ReturnType); } ilOfMethod.Emit(OpCodes.Stloc, methodresult); ilOfMethod.Emit(OpCodes.Ldarg_0); ilOfMethod.Emit(OpCodes.Ldfld, fieldInterceptor);//攔截方法參數賦值if (inheritMode) {//繼承傳遞代理類本身ilOfMethod.Emit(OpCodes.Ldarg_0); }else{//接口傳遞實現類ilOfMethod.Emit(OpCodes.Ldarg_0); ilOfMethod.Emit(OpCodes.Ldfld, fieldBeProxy); } ilOfMethod.Emit(OpCodes.Ldstr, method.Name); ilOfMethod.Emit(OpCodes.Ldloc, methodresult); ilOfMethod.Emit(OpCodes.Ldloc, localstart); ilOfMethod.Emit(OpCodes.Ldloc, localend); ilOfMethod.Emit(OpCodes.Callvirt, InterceptType.GetMethod("After")); }#endregion#region 事物提交及異常捕獲及回滾if (IsTransitinal) {//調用TransitionManage.DoCommitilOfMethod.Emit(OpCodes.Pop); ilOfMethod.Emit(OpCodes.Call, typeof(TransitionManage).GetMethod("DoCommit")); ilOfMethod.Emit(OpCodes.Ldarg_0);//開始catch模塊ilOfMethod.BeginCatchBlock(typeof(System.Exception));//調用TransitionManage.DoRollBackTransitional transition = (Transitional)method.GetCustomAttribute(typeof(Transitional));if (transition.AutoRollBack) { ilOfMethod.Emit(OpCodes.Pop); ilOfMethod.Emit(OpCodes.Call, typeof(TransitionManage).GetMethod("DoRollBack")); }else{//throw異常ilOfMethod.Emit(OpCodes.Pop); ilOfMethod.Emit(OpCodes.Rethrow); }//結束異常塊ilOfMethod.EndExceptionBlock(); }#endregion#region 處理返回值//調用完After方法后,將實現類的方法返回值的臨時變量再次壓棧用作代理方法的返回ilOfMethod.Emit(OpCodes.Ldloc, methodresult);// pop the stack if return voidif (method.ReturnType == typeof(void)) { ilOfMethod.Emit(OpCodes.Pop); }else{if (method.ReturnType.IsValueType) { ilOfMethod.Emit(OpCodes.Unbox_Any, method.ReturnType); }else{ ilOfMethod.Emit(OpCodes.Castclass, method.ReturnType); } }#endregion// completeilOfMethod.Emit(OpCodes.Ret); } }
以上就是NetCore中怎么利用Transitional自定義注解事物,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。