比如代码
:[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
将会转化(实际注入IL,这里反编译为了c#代码,更清晰)为:
<a href="http://blog.51cto.com/attachment/201204/171137854.png" target="_blank"></a>
<a href="http://blog.51cto.com/attachment/201204/171158941.png" target="_blank"></a>
从这里你就会清晰的明白这里实现静态注入了机制和原理了。我们需要做的目的就是从IL出发改变原来代码逻辑,注入我们的截取代码。使用Mono.Cecil具体代码在程序包MethodILInjectTask中。
MatchedMethodInterceptBase是应用于class上匹配该class多个methodattribute基类。rule为匹配规则。
[TestAOP2Attribute(Rule = "TestMethod1*")]
public class Class1
<a href="http://blog.51cto.com/attachment/201204/171319821.png" target="_blank"></a>
这里需要对于继承制该基类的标示class的所有满足rule的方法进行注入。
PropertyInterceptBase:属性注入,Action属性标识get,set方法。
[
TestAOPPropertyGetAttribute(Action = PropertyInterceptAction.Get)]
public int TestProperty
{
get;
set;
}
<a href="http://blog.51cto.com/attachment/201204/171427124.png" target="_blank"></a>
属性注入找出标示property,更具action选择get,set方法注入IL逻辑。
现在对于方法中获取attribute通过反射,性能存在一定问题。完全可以在class中注入属性,延时加载,Dictionary类级缓存来减少这方面损失,还暂时没考虑加入。
本文转自 破狼 51CTO博客,原文链接:http://blog.51cto.com/whitewolfblog/835177,如需转载请自行联系原作者