天天看點

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類級緩存來減少這方面損失,還暫時沒考慮加入。