Should my managed wrapper implement IDisposable?

  • Thread starter Thread starter Billy Porter
  • Start date Start date
B

Billy Porter

Greetings,

I got a class that wraps the System.Data.SqlClient.SqlConnection class (no
COM interaction). I'm not sure if I'm supposed to implement the IDisposable
pattern for this wrapper or not. Since one of it's members (SqlConnection)
implements this interface, I'm thinking maybe I ought to. But on the other
hand, those unmanaged resources has already been wrapped in the
SqlConnection class...

If so, how would my Dispose method look like?
I'm not really sure if I should look at SqlConnection as a managed or
unmanaged resource...
 
Only implement I disposable if you have resources which need to be
cleaned up after use. A popular one would be any open Streams, etc.

So in your wrapper, if you have things that need to be "cleaned" up,
then you'll want to implement IDisposable.

It's as easy as inheriting from it and creating the method

public void Dispose()
{
// do your cleanup here
}

It sounds like you should probably, since you're wrapping
SqlConnection. At the very minimum, have your dispose call your
SqlConnections's dispose function.

I'm not an expert on the topic, but those are my thoughts. Someone
else may have more sound reasoning.
 
If your class creates the SqlConnection (for example) only as needed and
makes sure it cleans it up in try...finally blocks , using(), etc. there is
no need for it to implement IDisposeable itself, since there isn't really
anything to clean up at that point.

On the other hand, if your class has a instantiation of the SqlConnection
scoped to the class for some reason then it needs to be IDisposeable so it
can clean that up.

The former approach is generally recommended anyway (for resource
conservation), so you should rarely have to implement IDisposeable.
 
Back
Top