态度决定高度、企图决定版图、格局决定结局

导航

基于Remoting透明代理的AOP实现

由于某些原因,这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

posted on 2006-12-19 22:12  flyingchen  阅读(711)  评论(1编辑  收藏  举报