目录
1. AOP介绍
2. Nuget安装Castle.Core
3. 自定义Interceptor拦截器
4. 自定义扩展方法,封装代理类的实现
5. Demo
1. AOP介绍
AOP: 面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的技术。
利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
AOP的使用场景主要包括日志记录、性能统计、安全控制、事务处理、异常处理等。
2. Nuget安装Castle.Core 3. 自定义Interceptor拦截器添加引用 using Castle.DynamicProxy;
InterceptorHelper类继承自StandardInterceptor,重写相关方法
此处日志仅输出到控制台,可以使用log4net记录日志配合使用
public class InterceptorHelper : StandardInterceptor { protected override void PreProceed(IInvocation invocation) { Trace.WriteLine($"{DateTime.Now}-->{invocation.Method.Name}-->执行前,入参:{string.Join(",",invocation.Arguments)}"); } protected override void PerformProceed(IInvocation invocation) { Trace.WriteLine($"{DateTime.Now}-->{invocation.Method.Name}-->执行中"); try { base.PerformProceed(invocation); } catch (Exception ex) { HandleException(ex); } } protected override void PostProceed(IInvocation invocation) { Trace.WriteLine($"{DateTime.Now}-->{invocation.Method.Name}-->执行后,返回值:{invocation.ReturnValue}"); } private void HandleException(Exception ex) { Trace.WriteLine($"执行异常,堆栈信息:{ex.StackTrace} ;异常信息:{ex.Message}"); } }4. 自定义扩展方法,封装代理类的实现
public static class ProxyExtension { public static T GetProxyInstance5. Demo(this T t) where T : class { return new ProxyGenerator().CreateClassProxy (new InterceptorHelper()); } }
若需要被动态代理类所代理并拦截,则父类的属性或方法必需是virtual。
public class TestAOP { public virtual string GetResult(string msg) { string str = $"{DateTime.Now:yyyy-mm-dd HH:mm:ss}---{msg}"; return str; } public virtual string GetResult2(string msg) { throw new Exception("throw Exception!"); } }
调用扩展方法,生成动态代理的对象:
var testaop= new TestAOP().GetProxyInstance(); testaop.GetResult("aaaaaaa"); testaop.GetResult2("bbb");
输出:
2022/1/18 16:29:17-->GetResult-->执行前,入参:aaaaaaa
2022/1/18 16:29:17-->GetResult-->执行中
2022/1/18 16:29:17-->GetResult-->执行后,返回值:2022-29-18 16:29:17---aaaaaaa
2022/1/18 16:29:17-->GetResult2-->执行前,入参:bbb
2022/1/18 16:29:17-->GetResult2-->执行中
引发的异常:“System.Exception”(位于xxx 中)
执行异常,堆栈信息: 在 xxx.TestAOP.GetResult2(String msg) 位置 E:xxxxTestAOP.cs:行号 19
在 Castle.Proxies.Invocations.TestAOP_GetResult2.InvokeMethodonTarget()
在 Castle.DynamicProxy.AbstractInvocation.Proceed()
在 JC_Vision_UI.Database.InterceptorHelper.PerformProceed(IInvocation invocation) 位置 E:xxxxInterceptorHelper.cs:行号 44 ;异常信息:throw Exception!
2022/1/18 16:29:17-->GetResult2-->执行后,返回值:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)