【发布时间】:2014-11-04 15:56:39
【问题描述】:
我正在尝试编写所有 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 param) 创建委托。
//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 del = CreateDelegate(channel, method)”行收到异常。
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)
我相信方法签名是正确的。
Channel 对象的确切类型是 System.Runtime.Remoting.Proxies.__TransparentProxy。但是,channel.getType() 返回 IFooService。这怎么可能?这种情况背后的魔力是什么?我想知道该模式提供了这个解决方案以及 __TransparentProxy 是如何工作的。是否有任何代码(项目)示例演示了这种架构?我认为这就是动态委托创建无法绑定目标方法的原因。
【问题讨论】:
-
我被困在同一点
标签: c# wcf delegates wcf-security remoting