天天看点

MSBuild + MSILInect实现编译时AOP-改变前后对比

比如代码:

MSBuild + MSILInect实现编译时AOP-改变前后对比

[testaopattribute(order = 1)]

public class1 testmethod1(int i, int j, class1 c) 

        { 

            console.writeline("ok"); 

            return new class1(); 

        }

public class testaopattribute : green.aop.methodinterceptbase 

    { 

        #region imethodinject members 

        public override bool executeing(green.aop.methodexecutioneventargs args) 

            console.writeline(this.gettype() + ":" + "executeing"); 

            return true; 

        } 

        public override green.aop.exceptionstrategy exceptioned(green.aop.methodexecutioneventargs args) 

            console.writeline(this.gettype() + ":" + "exceptioned"); 

            return green.aop.exceptionstrategy.handle; 

        public override void executesuccess(green.aop.methodexecutioneventargs args) 

            console.writeline(this.gettype() + ":" + "executesuccess"); 

        #endregion 

               #endregion 

    }

MSBuild + MSILInect实现编译时AOP-改变前后对比

将会转化(实际注入il,这里反编译为了c#代码,更清晰)为:

MSBuild + MSILInect实现编译时AOP-改变前后对比
MSBuild + MSILInect实现编译时AOP-改变前后对比

从这里你就会清晰的明白这里实现静态注入了机制和原理了。我们需要做的目的就是从il出发改变原来代码逻辑,注入我们的截取代码。使用mono.cecil具体代码在程序包methodilinjecttask中。

matchedmethodinterceptbase是应用于class上匹配该class多个methodattribute基类。rule为匹配规则。

[testaop2attribute(rule = "testmethod1*")]

public class class1 

MSBuild + MSILInect实现编译时AOP-改变前后对比

这里需要对于继承制该基类的标示class的所有满足rule的方法进行注入。

propertyinterceptbase:属性注入,action属性标识get,set方法。

MSBuild + MSILInect实现编译时AOP-改变前后对比

[testaoppropertygetattribute(action = propertyinterceptaction.get)] 

       public int testproperty 

       { 

           get; 

           set; 

       }

MSBuild + MSILInect实现编译时AOP-改变前后对比
MSBuild + MSILInect实现编译时AOP-改变前后对比

属性注入找出标示property,更具action选择get,set方法注入il逻辑。

现在对于方法中获取attribute通过反射,性能存在一定问题。完全可以在class中注入属性,延时加载,dictionary类级缓存来减少这方面损失,还暂时没考虑加入。