我正在尝试创建一个RealProxy,以便实现一些缓存和其他一些功能。我已经检查了GetTransparentProxy返回的类型,它看起来是正确的,但是如果我在它上面调用InvokeMember,那么代理最终会调用它自己,并且我得到一个堆溢出。有人能指出我做错了什么吗?
public class CachedWebServiceProxy<T> : RealProxy
{
private Type _typeOfProxy;
public CachedWebServiceProxy(Type typeOfProxy) : base(typeOfProxy)
{
_typeOfProxy = typeOfProxy;
}
public override System.Runtime.Remoting.Messaging.IMessage Invoke(System.Runtime.Remoting.Messaging.IMessage msg)
{
var methodCall = msg as IMethodCallMessage;
var methodInfo = methodCall.MethodBase as MethodInfo;
var proxy = GetTransparentProxy();
var result = _typeOfProxy.InvokeMember(methodCall.MethodName, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, proxy, methodCall.Args);
return new ReturnMessage(result, null, 0, methodCall.LogicalCallContext, methodCall);
}
}
class CachedWebServiceChannelFactory<T> : ChannelFactory<T>
{
public CachedWebServiceChannelFactory(Binding binding, EndpointAddress endpoint) : base(binding, endpoint)
{ }
public CachedWebServiceChannelFactory(string endpointConfigurationName)
: base(endpointConfigurationName)
{ }
public override T CreateChannel(EndpointAddress address, Uri via)
{
var extendedProxy = new CachedWebServiceProxy<T>(typeof(T));
return (T)extendedProxy.GetTransparentProxy();
}
}发布于 2013-07-08 16:43:53
好的,基本的问题是我假设我的代码包装了透明代理,而实际上透明代理包装了我的类。我想我能做的就是创建一个基本代理的实例,调用这个代理上的方法并返回结果。
因为我的类实际上是透明代理调用的基类,所以GetTransparentProxy只创建了我的类的一个新实例(这又创建了另一个新实例,等等)。
我现在意识到我应该在ChannelFactory中做类似的事情。这是一个子类,所以我可以在自己的逻辑中包装base.*方法,就像我希望在代理类中做的那样。我现在要做的是从一个基本方法中获取通道的一个实例,然后将它传递给我的RealProxy类,然后使用反射在通道对象上调用所需的方法。
代码如下:
public class CachedWebServiceProxy<T> : RealProxy
{
private Type _typeOfProxy;
public object _channel;
public CachedWebServiceProxy(Type typeOfProxy, object channel)
: base(typeOfProxy)
{
_typeOfProxy = typeOfProxy;
_channel = channel;
}
public override System.Runtime.Remoting.Messaging.IMessage Invoke(System.Runtime.Remoting.Messaging.IMessage msg)
{
var methodCall = msg as IMethodCallMessage;
var methodInfo = methodCall.MethodBase as MethodInfo;
object result = null;
result = methodInfo.Invoke(_channel, methodCall.Args);
return new ReturnMessage(result, null, 0, methodCall.LogicalCallContext, methodCall);
}
}
public class CachedWebServiceChannelFactory<T> : ChannelFactory<T>
{
public CachedWebServiceChannelFactory(Binding binding, EndpointAddress endpoint)
: base(binding, endpoint)
{ }
public CachedWebServiceChannelFactory(string endpointConfigurationName)
: base(endpointConfigurationName)
{ }
public override T CreateChannel(EndpointAddress address, Uri via)
{
T innerChannel = base.CreateChannel(address, via);
var extendedProxy = new CachedWebServiceProxy<T>(typeof(T), innerChannel);
return (T)extendedProxy.GetTransparentProxy();
}
}乔
https://stackoverflow.com/questions/17449046
复制相似问题