HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

WCF wrapper implementing dispose-finalize pattern

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
finalizewrapperdisposeimplementingpatternwcf

Problem

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 : IDisposable where TProxy : class
{
private string _endpointAddress;
public TProxy Service { get; private set; }

public WCFClientWrapper(string endpointAddress)
{
_endpointAddress = endpointAddress;

var factory = new ChannelFactory(new NetTcpBinding(), new EndpointAddress(endpointAddress));
Service = factory.CreateChannel();

(Service as IClientChannel).Faulted += WCFClientWrapper_Faulted;
}

private TProxy CreateChannel(string endpointAddress)
{
var factory = new ChannelFactory(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();

Solution

Given that much of the code seems to rely on Service being an IClientChannel, and the name of the class implies as such, it may be worth simply adding IClientChannel to your type constraints and remove all the type conversion code.

Building upon that thought, I notice that IClientChannel extends IChannel, and everything you use seems to be present on IChannel. You may consider using that interface instead, and renaming your class to reflect that it is not limited to IClientChannel.

Context

StackExchange Code Review Q#7862, answer score: 2

Revisions (0)

No revisions yet.