Aop“面向切面编程”,与OOP“面向对象编程”一样是一种编程思路。个人理解:在不改变原有逻辑的基础上,注入其他行为。
基础代码(仿MVC拦截器实现)
- namespace HGL.Toolkit.Aop
- {
- [AttributeUsage(AttributeTargets.Class,AllowMultiple=true)]
- publicsealedclassAopAttribute:ContextAttribute,IContributeObjectSink
- {
- publicAopAttribute():base("Aop"){}
- //实现IContributeObjectSink接口当中的消息接收器接口
- publicIMessageSinkGetObjectSink(MarshalByRefObject obj,IMessageSinknext)
- {
- returnnewAopProxy(next);
- }
- }
- [AttributeUsage(AttributeTargets.Method,AllowMultiple=true)]
- publicclassAopMethodAttribute:Attribute
- {
- /// <summary>
- /// 方法执行之前,执行代码
- /// </summary>
- publicvirtualboolOnMethodExecuting(System.Web.HttpContext context)
- {
- returntrue;
- }
- /// <summary>
- /// 方法执行之后,执行代码
- /// </summary>
- publicvirtualboolOnMethodExecuted(System.Web.HttpContext context)
- {
- returntrue;
- }
- }
- }
- namespace HGL.Toolkit.Aop
- {
- publicsealedclassAopProxy:IMessageSink
- {
- //下一个接收器
- privateIMessageSink nextSink;
- publicIMessageSinkNextSink
- {
- get{return nextSink;}
- }
- publicAopProxy(IMessageSink nextSink)
- {
- this.nextSink = nextSink;
- }
- //同步处理方法
- publicIMessageSyncProcessMessage(IMessage msg)
- {
- IMessage retMsg =null;
- //方法调用消息接口
- IMethodCallMessage call = msg asIMethodCallMessage;
- var attributes =Attribute.GetCustomAttributes(call.MethodBase,typeof(AopMethodAttribute));
- //如果被调用的方法没打AopMethodAttribute标签
- if(call ==null|| attributes.Count()==0)
- {
- retMsg = nextSink.SyncProcessMessage(msg);
- }
- //如果打了AopMethodAttribute标签
- else
- {
- foreach(var attribute in attributes)
- {
- var obj = attribute.GetType();
- var executing = obj.GetMethod("OnMethodExecuting");
- if(executing !=null)
- {
- var context=System.Web.HttpContext.Current;
- executing.Invoke(attribute,newobject[]{ context });
- }
- }
- retMsg = nextSink.SyncProcessMessage(msg);
- foreach(var attribute in attributes)
- {
- var obj = attribute.GetType();
- var executed = obj.GetMethod("OnMethodExecuted");
- if(executed !=null)
- {
- var context =System.Web.HttpContext.Current;
- executed.Invoke(attribute,newobject[]{ context });
- }
- }
- }
- return retMsg;
- }
- //异步处理方法(不需要)
- publicIMessageCtrlAsyncProcessMessage(IMessage msg,IMessageSink replySink)
- {
- returnnull;
- }
- }
- }
使用注意:
- 1.使用到Aop的类必须继承ContextBoundObject
- 2.使用到Aop的方法存在的类必须添加[Aop]特性
- 3.哪个方法需要实现Aop,就给那个方法添加[AopMethod]特性
- AopMethod未实现任何业务逻辑,使用者需要重写该attribute
- /// <summary>
- /// 方法执行之前,执行代码
- /// </summary>
- publicvirtualboolOnMethodExecuting()
- {
- returntrue;
- }
- /// <summary>
- /// 方法执行之后,执行代码
- /// </summary>
- publicvirtualboolOnMethodExecuted()
- {
- returntrue;
- }
待续......(将执行前和执行后的方法使用代理委托机制,实现二次开发)
出处:https://www.bbsmax.com/A/lk5ar87md1/