對於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