对于WCF客户端,我有一个IServiceProxyFactory
接口来设置凭据。是否有可能摆脱服务类中的TClient泛型类型
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());
OR (更新)
Service<ServiceClient1>.Use(svc => svc.Method());
有没有更好的办法,而不是使用
ICommunicationObject
为Close()
和Abort()
?
嗯......你可以改变类上的约束是IServiceProxy,从类签名删除TClient,并添加TClient和该方法的约束? –
JerKimball
2013-03-24 02:12:26