首页 > 开发 > .Net > 正文

.NET :消息与AOP(二)

2020-02-03 16:00:37
字体:
来源:转载
供稿:网友
using system;
using system.runtime.remoting ;
using system.runtime.remoting.services ;
using system.runtime.remoting.activation ;
using system.runtime.remoting.proxies ;
using system.runtime.remoting.messaging ;

/*
本程序说明了截获是如何进行的,以及真实代理和透明代理之间的关系及交互。
*/
namespace intercept_example
{
class class1
{
[stathread]
static void main(string[] args)
{
example exa = new example("sky" ) ;
exa.say_hello() ;
}
}

//定义一个真实代理,用于实现一个特定的预处理和后处理
public class interceptproxy : realproxy
{
private readonly marshalbyrefobject target ;

public interceptproxy(marshalbyrefobject obj ,type type) :base(type)
{
this.target = obj ;
}


public override imessage invoke(imessage msg)
{
imethodcallmessage call = (imethodcallmessage)msg ;

//如果触发的是构造函数,此时target的构建还未开始
iconstructioncallmessage ctor = call as iconstructioncallmessage ;
if(ctor != null)
{
system.console.writeline("转发构造函数调用!") ;

realproxy default_proxy = remotingservices.getrealproxy(this.target) ;

default_proxy.initializeserverobject(ctor) ;
marshalbyrefobject tp = (marshalbyrefobject)this.gettransparentproxy() ;

return enterpriseserviceshelper.createconstructionreturnmessage(ctor,tp);

}

system.console.writeline("预处理中......") ;
system.threading.thread.sleep(5000) ;

imethodreturnmessage result_msg = remotingservices.executemessage(this.target ,call) ;

system.console.writeline("后处理中......") ;
system.threading.thread.sleep(5000) ;
system.console.writeline("后处理结束!") ;

return result_msg ;

}
}



//定义一个特性,该特性可以将上面的真实代理与运用该特性的class联系起来
[attributeusage(attributetargets.class)]
public class interceptproxyattribute : proxyattribute
{
//得到透明代理
public override marshalbyrefobject createinstance(type servertype)
{
//未初始化的实例
marshalbyrefobject target = base.createinstance (servertype);

interceptproxy rp = new interceptproxy(target ,servertype) ;

return (marshalbyrefobject)rp.gettransparentproxy() ;
}
}

[interceptproxy]
public class example : contextboundobject//放到特定的上下文中,该上下文外部才会得到该对象的透明代理
{
private string name ;
public example(string a)
{
this.name = a ;
}

public void say_hello()
{
console.writeline("hello ! " + name ) ;
}
}

/*
*(1) 当调用方和被调方位于不同的上下文时,调用方得到的是被调对象的透明代理。透明代理会将方法调用打包成一个imessage对象,并传给实际代理的invoke方法。
* invoke方法的默认实现只是将imessage对象传递到后面的通道(如堆栈生成器等)中。我们可以定制自己的真实代理,重写invoke方法,为之加上预处理和后处理。
*(2)通过代理特性(如interceptproxyattribute)(从proxyattribute继承)将真实代理与目标class关联起来。这个代理特性主要重写proxyattribute的createinstance
* createinstance方法,在该方法中,在目标对象的外围包裹上真实代理(如interceptproxy),而返回该真实代理的透明代理。
* (3)在程序中,不能直接通过真实代理来调用目标对象的方法,因为真实代理处理的是消息对象(imessage),它是基于消息世界的。
* (4)只有持有透明代理的引用,我们才有可能加入截获(前处理和后处理)。
* (5)派生于contextboundobject的类,我们只能得到它的透明代理;派生于mashalbyrefobject的类的对象,我们可能得到它的透明代理或者直接引用,这取决于被调方和目
* 标对象是否位于同一上下文中;不从这两个类派生的类的对象,我们只能得到它的直接引用。
*/



}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表