本文转载自微信公众号《UP科技控》,作者conan5566。转载本文请联系UP技控公众号。AOP是AspectOrientedProgramming的缩写,意思是:面向方面的编程,一种通过预编译和运行时动态代理实现程序功能统一维护的技术。AOP是OOP的延续,是软件开发的热点……函数式编程的衍生范式。AOP可以用来隔离业务逻辑的各个部分,从而降低业务逻辑各个部分之间的耦合度,提高程序的复用性,同时提高开发效率。动态代理是一种实现AOP的方式,即我们在开发过程中不需要处理切面(日志等),而是在运行时通过动态代理自动完成。CastleDynamicProxy是一个实现动态代理的框架,被很多优秀的项目用来实现AOP编程,EFCore,Autofac等为业务类添加AOP拦截器//////为业务类添加AOP拦截器.///publicclassInterceptorAttribute:PlutoStudio.Aop.InterceptorAttribute{//////拦截方法的执行,如果当前方法有拦截处理器,则执行该处理器。//////拦截调用目标对象publicoverridevoidIntercept(IInvocationinvocation){varmethod=invocation.Method;varprocessors=method.GetCustomAttributes(typeof(IInterceptorProcessor),true).Cast().ToList();processors.ForEach(p=>PlutoStudio.MefContainer.Container.ComposeParts(p));if(processors.Count>0){processors.ForEach(p=>p.PreProcess(invocation));try{invocation.Proceed();processors.ForEach(p=>p.PostProcess(invocation,null));}catch(Exceptionex){processors.ForEach(p=>p.PostProcess(invocation,ex));throw;}}else{invocation.Proceed();}}}//////拦截器处理器接口。///publicinterfaceIInterceptorProcessor{//////拦截器处理方法在目标方法执行之前执行。//////拦截的目标对象voidPreProcess(IInvocationinvocation);//////拦截器处理方法,执行完目标方法后执行。//////拦截目标对象///目标方法异常voidPostProcess(IInvocationinvocation,Exceptionex);}日志处理器可以将目标方法的信息保存到日志系统//////日志处理器可以将目标方法的信息保存到日志系统。///[AttributeUsage(AttributeTargets.Method,AllowMultiple=false,Inherited=true)]publicclassLogAttribute:Attribute,IInterceptorProcessor{[Import(AllowDefault=true)]publicILogLog{get;set;}//////目标方法执行完成后执行,目标方法的相关信息会记录在这里,并写入日志系统。/////////publicvoidPostProcess(IInvocationinvocation,Exceptionex){if(Log!=null){var@class=invocation.TargetType.FullName;varmethod=invocation.Method.Name;varparameterNames=invocation.Method.GetParameters().Select(p=>p.Name).ToList();varargs=invocation.Arguments;varparameters=newDictionary();for(inti=0;ii.GetMethod().Name!=invocation.Method.Name).Select(GetStack);varlog=newTraceLog{Class=@class,Method=方法,Parameter=参数,ReturnValue=returnValue,Strack=stack,Exception=ex,};Log.Custom(log);}}privateobjectGetStack(StackFrameframe){varmethod=frame.GetMethod();vartype=method.ReflectedType;如果(类型。完整Name.StartsWith("Castle.Proxies")){type=type.BaseType;}returnnew{Method=method.Name,Type=type.FullName,File=frame.GetFileName(),Line=frame.GetFileLineNumber(),};}publicvoidPreProcess(IInvocationinvocation){}}//////系统跟踪日志,由///publicclassTraceLog{/////生成/当前日志记录的目标类。///publicstringClass{get;internalset;}//////当前日志跟踪的异常。///publicExceptionException{get;internalset;}//////当前日志记录的目标方法。///publicstringMethod{get;internalset;}//////当前日志记录的目标方法的参数。///publicDictionaryParameter{get;internalset;}//////当前日志记录的目标方法的返回值。///publicobjectReturnValue{get;internalset;}//////当前日志记录的目标方法的调用栈。///publicIEnumerable