基於Remoting透明代理的AOP實現

來源:互聯網
上載者:User

由於某些原因,這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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.