由於某些原因,這2天又拿起了關於AOP方面的資料來學習下。每一次的學習,都有更多的一些認識。在.Net下基於Remoting的實現,應該算是能“最大發揮“的實現了:),動態織入的實現,讓其靈活而強大,當然也有其缺陷,比如方法調用要被攔截的類必須繼承與ContextBoundObject對象,對於單繼承的C#而言,缺陷不小!
參考了Bruce Zhang blog上的AOP資源SqlCenter中AOP實現,自己寫了一個小程式,實現了方法調用前後的攔截,僅僅是個toy而已!
實現一個計算機,能夠進行2個int類型資料計算,通過子類實現具體演算法,當然也是非常簡單的+-*/
public abstract class Calculator:ContextBoundObject
{
public virtual int Perform(int a ,int b)
{
return -1;
}
}
給出2個實現,加法和減法計算
public class AddCalculator:Calculator
{
public override int Perform(int a ,int b)
{
return a + b;
}
}
public class SubCalculator:Calculator
{
public override int Perform(int a ,int b)
{
return a-b;
}
}
現在在這個基礎上,我要記錄下調用過程,已經一些描述資訊,ok,這裡就是利用AOP的開始:)
請注意,上面是啥?是的,上面的實現是我的主要任務(核心關注)。出現AOP代碼了嗎?沒有!(當然你也許會說Calculator繼承了ContextBoundObject:) ,完全有理!)
不管,繼續我們的實現。下面就是我基於透明代理的一些實現:
public class LogProxy:RealProxy
{
MarshalByRefObject myMarshalByRefObject;
[PermissionSet(SecurityAction.LinkDemand)]
public LogProxy(Type myType):base(myType)
{
myMarshalByRefObject = (MarshalByRefObject)Activator.CreateInstance((myType));
}
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure)]
public override IMessage Invoke(IMessage msg)
{
IMethodCallMessage call = (IMethodCallMessage) msg;
//方法開始
Start(call);
IMethodReturnMessage back = null;
back = RemotingServices.ExecuteMessage(myMarshalByRefObject, call);
//方法調用完成
End(ref back);
return back;
}
private void Start(IMethodCallMessage call)
{
/*
類比給出對方法調用的描述
*/
Console.WriteLine("Start....");
Console.WriteLine("Method:"+call.MethodName.ToString());
Console.Write("\t");
for(int i =0 ;i<call.Args.Length;i++)
Console.Write("The Args Is:{0},",call.Args[i]);
Console.WriteLine("");
}
public void End(ref IMethodReturnMessage call )
{
//擷取傳回值
Console.WriteLine("\tThe Result is:{0}",call.ReturnValue);
}
}
下面請關注下client是如何調用的:
public static void Main()
{
LogProxy p = new LogProxy(typeof(AddCalculator));
Calculator c = (AddCalculator)p.GetTransparentProxy();
int result = c.Perform(3,3);
Console.ReadLine();
}
通過client調用,成功獲得結果:
大膽的嘗試吧!
參考:
http://www.brucezhang.com/?page_id=41
http://www.cnblogs.com/flyingchen/archive/2006/11/06/552270.html
http://www.cnblogs.com/flyingchen/archive/2006/10/24/538757.html
http://www.cnblogs.com/flyingchen/archive/2006/10/21/535980.html