I tried to implement the dispose-finalize pattern on this WCF wrapper.
Do you have any comments about this? Something I missed?
namespace System.ServiceModel
{
public class WCFClientWrapper<TProxy> : IDisposable where TProxy : class
{
private string _endpointAddress;
public TProxy Service { get; private set; }
public WCFClientWrapper(string endpointAddress)
{
_endpointAddress = endpointAddress;
var factory = new ChannelFactory<TProxy>(new NetTcpBinding(), new EndpointAddress(endpointAddress));
Service = factory.CreateChannel();
(Service as IClientChannel).Faulted += WCFClientWrapper_Faulted;
}
private TProxy CreateChannel(string endpointAddress)
{
var factory = new ChannelFactory<TProxy>(new NetTcpBinding(), new EndpointAddress(endpointAddress));
return factory.CreateChannel();
}
void WCFClientWrapper_Faulted(object sender, EventArgs e)
{
DisposeService();
Service = CreateChannel(_endpointAddress);
}
public void Dispose(bool disposing)
{
if (disposing)
{
// get rid of managed resources
}
DisposeService();
GC.SuppressFinalize(this);
}
private void DisposeService()
{
IClientChannel serviceChannel = Service as IClientChannel;
if (serviceChannel == null)
return;
bool success = false;
try
{
(Service as IClientChannel).Faulted -= WCFClientWrapper_Faulted;
if (serviceChannel.State != CommunicationState.Faulted)
{
serviceChannel.Close();
success = true;
}
}
finally
{
if (!success)
{
serviceChannel.Abort();
}
}
}
public void Dispose()
{
Dispose(true);
}
~WCFClientWrapper()
{
Dispose(false);
}
}
}