比如代碼
:[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,如需轉載請自行聯系原作者