【发布时间】:2015-04-19 09:29:39
【问题描述】:
对于 WCF 客户端,我有一个 IServiceProxyFactory 接口来设置凭据。
public interface IServiceProxyFactory<T>
{
T GetServiceProxy();
}
public class ServiceProxy1 : IServiceProxyFactory<ServiceClient1>
{
public ServiceClient1 GetServiceProxy()
{
var client = new ServiceClient1();
// set credentials here
return client;
}
}
public class ServiceProxy2 : IServiceProxyFactory<ServiceClient2> {
// ...
}
从问题What is the best workaround for the WCF client `using` block issue?,我创建了一个助手如下:
public static class Service<TProxy, TClient>
where TProxy : IServiceProxyFactory<TClient>, new()
where TClient : ICommunicationObject
{
public static IServiceProxyFactory<TClient> proxy = new TProxy();
public static void Use(Action<TClient> codeBlock)
{
TClient client = default(TClient);
bool success = false;
try
{
client = proxy.GetServiceProxy();
codeBlock(client);
((ICommunicationObject)client).Close();
success = true;
}
finally
{
if (!success)
{
((ICommunicationObject)client).Abort();
}
}
}
}
我将助手用作:
Service<ServiceProxy1, ServiceClient1>.Use(svc => svc.Method());
问题:
-
有没有办法让我摆脱
TClient或TProxy(更新) 类型,以便我可以使用:Service<ServiceProxy1>.Use(svc => svc.Method());或(更新)
Service<ServiceClient1>.Use(svc => svc.Method()); 有没有比将
ICommunicationObject用于Close()和Abort()更好的方法?
【问题讨论】:
-
嗯……你能把类的约束改成IServiceProxy
,把TClient从类签名中去掉,然后把TClient和约束加到方法里吗?