1
我想確保在使用服務後關閉WCF服務客戶端狀態。關閉服務客戶端狀態的模式
我執行下面的代碼,以確保:
public static class ServiceClientFactory
{
public static ServiceClientHost<T> CreateInstance<T>() where T : class, ICommunicationObject, new()
{
return new ServiceClientHost<T>();
}
}
public class ServiceClientHost<T> : IDisposable where T : class, ICommunicationObject, new()
{
private bool disposed;
public ServiceClientHost()
{
Client = new T();
}
~ServiceClientHost()
{
Dispose(false);
}
public T Client { get; private set; }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposeManagedResources)
{
if(!disposed)
{
if(disposeManagedResources)
{
Client.Close();
Client = null;
}
disposed = true;
}
}
}
用法:
using (var host = ServiceClientFactory.CreateInstance<MySericeClient>())
{
host.Client.DoSomething();
}
我想知道是否有更好的/優雅的解決方案比我的?
感謝您的任何提示!
對於最後的陳述你會有什麼建議? – 2012-06-16 12:30:28