我试图编写所有wcf代理方法都经过此方法并缓存返回值的泛型方法。泛型方法是
public T CallService<T>(Delegate del, object[] args)
{
// begin caching logic
// ...
// if value is cached, return it. Otherwise call app site.
// end caching logic
return (T)del.DynamicInvoke(args);
}为了实现这一点,我需要在下面链接的帮助下动态创建委托。
Creating delegates dynamically with parameter names
简单地说,我想要的是为通道方法IFooService.Bar(string )创建委托。
//wcf contract
public interface IFooService
{
int Bar(string param);
}
//sample proxy
public class Foo
{
public int Bar(string param)
{
IFooService channel = null;
int result;
try
{
// we assume that wcf channel has created here
ChannelFactory<IFooService> channelFactory = new ChannelFactory<IFooService>(binding, remoteAddress);
IFooService channel = channelFactory.CreateChannel();
var parameters = MethodBase.GetCurrentMethod().GetParameters();
object[] args = new object[parameters.Length];
args[0] = param;
MethodInfo method = typeof(IFooService).GetMethod("Bar");
Delegate del = CreateDelegate(channel, method);
result = CallService<int>(del, args);
((ICommunicationObject)channel).Close();
}
catch (Exception ex)
{
((ICommunicationObject)channel).Abort();
throw;
}
return result;
}
}当应用程序运行时,我在"Delegate =CreateDelegate(通道,方法)“行中得到异常。
Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.
at System.Delegate.CreateDelegate(Type type, Object firstArgument, MethodInfo method, Boolean throwOnBindFailure)我相信方法签名是正确的。
通道对象的确切类型是System.Runtime.Remoting.Proxies.__TransparentProxy.但是,channel.getType()返回IFooService。这怎么可能?这种情况背后的魔力是什么?我想知道模式提供了这个解决方案,以及__TransparentProxy是如何工作的。是否有任何代码(项目)示例演示此体系结构?我认为这就是动态委托创建不能绑定目标方法的原因。
发布于 2015-10-04 02:21:54
当我尝试的时候,我得到了同样的例外
MethodInfo mi = typeof(IMyInterf).GetMethod(MyMethod);
Delegate d = Delegate.CreateDelegate(typeof(myMethodDelegate), channel, mi);
d.DynamicInvoke(args);当我将其更改为:
Delegate d = Delegate.CreateDelegate(typeof(myMethodDelegateX), null, mi);
d.DynamicInvoke(channel, args);如果myMethodDelegate看起来像
delegate void myMethodDelegate(T1 arg1, T2 arg2, ...);然后,根据myMethodDelegateX调用,myMethodDelegateX必须具有将通道作为第一个参数传递的实例参数,然后是实际的方法参数:
delegate void myMethodDelegateX(IMyInterf targetInstance, T1 arg1, T2 arg2, ...);我在Delegate.CreateDelegate(Type,Object,MethodInfo)重载的MSDN文档中找到了这个变体,它在那里被称为“打开实例”方法,它与我的WCF通道一起工作,在这里我总是得到“无法绑定到目标方法.”。
编辑:当然,d.DynamicInvoke(通道,args)是胡说八道,你必须把这些参数放到一个新的数组中。
https://stackoverflow.com/questions/26739486
复制相似问题