您的位置:首页 > 编程语言

关于代理类的使用情景和基本代码

2009-10-22 10:06 453 查看
当你做好一个项目的时候,你突然发现运行起来比较慢,各种异常又没有写进日志里面,这种想做一些监测,比如看某个类每个方法执行时间,把异常进行管理,但没有人愿意把每个方法都写上监测逻辑,那这时代理就有了使用场景,主要是只要修改不多的程序,就可以让某类在方法或属性被调用时,先访问某个方法.具体如下:

代码:

被代理的类

public class Class2 : MarshalByRefObject
{
private Class2()
{
}
public static Class2 CreateInstance()
{
Class2 mobj = new Class2();
proxytem realProxy = new proxytem(typeof(Class2),mobj);
Class2 refObj = (Class2)realProxy.GetTransparentProxy();
return refObj;
}
public int sum()
{
return 9;
}
}

proxytem 类

public class proxytem : RealProxy
{
MarshalByRefObject myMarshalByRefObject;

public proxytem(Type myType, MarshalByRefObject mobj)
: base(myType)
{
myMarshalByRefObject = mobj;
}
public override System.Runtime.Remoting.Messaging.IMessage Invoke(System.Runtime.Remoting.Messaging.IMessage message)
{
System.Runtime.Remoting.Messaging.IMessage retMsg = null;
if (message is IConstructionCallMessage)
{
IConstructionCallMessage ccm = (IConstructionCallMessage)message;
RemotingServices.GetRealProxy(myMarshalByRefObject).InitializeServerObject(ccm);
ObjRef objRef = RemotingServices.Marshal(myMarshalByRefObject);
RemotingServices.Unmarshal(objRef);
retMsg = EnterpriseServicesHelper.CreateConstructionReturnMessage(ccm, (MarshalByRefObject)this.GetTransparentProxy());
}
else if (message is IMethodCallMessage)
{
IMethodCallMessage mcm = (IMethodCallMessage)message;
DateTime start = DateTime.Now;
//执行方法调用
retMsg = RemotingServices.ExecuteMessage(myMarshalByRefObject, mcm);
IMethodReturnMessage mrm = (IMethodReturnMessage)retMsg;
DateTime end = DateTime.Now;
//有了start和end就可以统计时间
Exception ex = mrm.Exception;
//如果没有异常,就进行序列化测试,SerializeHelper这个类可以检测对象是否可序列化,具体百度一下
//if (ex == null)
//{
// try
// {
// SerializeHelper.DataContractSerializer(mrm.ReturnValue);
// }
// catch (Exception e)
// {
// ex = e;
// }
//}
ObjRef objRef = RemotingServices.Marshal(myMarshalByRefObject);//获得原来的类的实例
MethodInfo mi = mcm.MethodBase.DeclaringType.GetMethod(mcm.MethodName);//获得方法信息
Activator.CreateInstance(mi.ReturnType);//可以获得方法反回类型的实例,这就保证方法不会报错,一定会返回一个new出来的实例
object a= ((ReturnMessage)retMsg).ReturnValue;//可以得到返回值.
}

return retMsg;
}
}

调用:

Class2 c2 = Class2.CreateInstance();
int i =c2.sum();

1.被代理的类要继承MarshalByRefObject类,RealProxy是系统的一个基本代理类,new RealProxy(MarshalByRefObject)后,如果访问MarshalByRefObject实例的方法,就会调用RealProxy.Invoke的方法,利用这一点,找个类继承RealProxy,把实例也传进去,然后重写invoke,在invoke里面利用 retMsg = RemotingServices.ExecuteMessage(myMarshalByRefObject, mcm);
来执行方法,同时也可以做很多统计工作
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: