I see a lot of code like this:
public class MyWcfService : IMySerciceContract, IDisposable
{
private DatabaseOperations _dataAccess;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
_dataAccess.Dispose();
}
}
Where the class MyWcfService will be hosted in IIS or WAS, where no one will explicitly call Dispose on it. My thought is that it's pointless to have this class implement IDisposable, and you'd be better off wrapping the use of _dataAccess in a using statement. As I understand it, the expectation of a class that implements IDisposable is that a user of that class will instantiate it in a using block declaration. Is the above example bad practice considering no user will explicitly call Dispose? If we rely on GC to clean up as in the above example, does the GC even call Dispose, or just the finalizer?
"DatabaseOperations _dataAccess" is a class member, and is 'owned' by your class. It is IDisposable, so your class should be too. And you should always implement the full standard dipose pattern for consistency.
If _dataAccess were a local variable inside a class method, which you used and discarded within method scope, then a using block would be appropriate.
As a rule, you want to code in such a way as to give the maximum degree of cleanup control to users of your code. That means being IDisposable if any of your members are. But for non-member IDisposable objects, then 'using' is the way to go.
Of course, the same then applies to consumers of your class. If they embed your class as a member field, they should make their class IDisposable. Otherwise, they can use 'using' with your class objects.. and so on.