对于 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> {
// ...
}
从问题WCF 客户端“使用”块问题的最佳解决方法是什么?,我创建了一个助手,如下所示:
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
orTProxy
(更新的)类型,以便我可以使用:Service<ServiceProxy1>.Use(svc => svc.Method());
或(更新)
Service<ServiceClient1>.Use(svc => svc.Method());
有没有比使用
ICommunicationObject
forClose()
and更好的方法Abort()
?