At work, I’ve found a helper class to manage WCF Services which implements IDisposable and has a ServiceAgent that derives from System.ServiceModel.ClientBase. The Dispose() method closes all the opened WCF services. The helper exposes methods that wraps calls to the methods of the ServiceAgent. Each method is build on that pattern:
public void WCFMethod1()
{
using(this)
{
this.ServiceAgent.WCFMethod1();
}
}
public override void Dispose()
{
try
{
this.ServiceAgent.Close();
}
catch
{
this.ServiceAgent.Abort();
}
finally
{
this.ServiceAgent = null;
}
}
Here’s the question: is the use of using(this) a good practice?
I don’t like it. I think that class should be a) disposed once b) by code that instantiated it.
IDisposableusually understood as way to implement RAII pattern. MSDN explicitly states:So users will find this behavior confusing, so i recommend to design the class so that it is instantiated per call: