我正在尝试创建一个通用的WCF服务调用程序实用程序,但是我对泛型,代理和lambda的了解使我在最后的障碍中失败了。
我希望能够封装调用我的WCF Web服务的身份验证和预期处理,这样我就可以只使用接口,请求和响应类来使用Web服务。
我不明白我如何传递我想要执行的方法名称 - 我已经尝试了Func<>路线,但我感到困惑,因为我得到一个递归错误与我在下面实现的。我宁愿不去硬编码的字符串/反射路径 - 我希望这是一个强类型的类。
请帮忙!
谢谢
public static TResponse Invoke<TService, TRequest, TResponse>(TRequest request, Func<TService, TRequest, TResponse> methodToExecute, string endpointConfigurationName) where TResponse : class
{
ChannelFactory<TService> channel = new ChannelFactory<TService>(endpointConfigurationName);
// attach auth credentials
channel.Credentials.UserName.UserName = "myUserName";
channel.Credentials.UserName.Password = "myPassword";
// create a proxy for the channel
TService proxy = channel.CreateChannel();
TResponse response;
try
{
response = methodToExecute(proxy, request);
channel.Close();
}
catch
{
// abort or close in a fail-safe manner
if (channel.State == CommunicationState.Faulted)
{
channel.Abort();
}
else
{
channel.Close();
}
throw;
}
return response;
}
答案 0 :(得分:1)
这是我的尝试。我的版本没有请求类型作为参数。我展示了我希望你如何使用它(你没有展示你计划如何调用你的,但我怀疑问题出在调用中,而不是方法本身)。
private class Response {}
private interface IService
{
Response MyMethod(object i);
}
public static void Foo()
{
object request = 1;
Response response = Invoke((IService service) => service.MyMethod(request), "endpoint");
}
public static TResponse Invoke<TService, TResponse>(Func<TService, TResponse> methodToExecute, string endpointConfigurationName) where TResponse : class
{
ChannelFactory<TService> channel = new ChannelFactory<TService>(endpointConfigurationName);
// attach auth credentials
channel.Credentials.UserName.UserName = "myUserName";
channel.Credentials.UserName.Password = "myPassword";
// create a proxy for the channel
TService proxy = channel.CreateChannel();
TResponse response;
try
{
response = methodToExecute(proxy);
channel.Close();
}
catch
{
// abort or close in a fail-safe manner
if (channel.State == CommunicationState.Faulted)
{
channel.Abort();
}
else
{
channel.Close();
}
throw;
}
return response;
}