I use regular Sql* objects to query my database :
// conn is a SqlConnection
// transaction is a SqlTransaction
using(var cmd = new SqlCommand(someSelectQuery, conn, transaction))
using(var reader = cmd.ExecuteReader())
{
...
}
I am to write a wrapper, that would pack the new SqlCommand() and the cmd.ExecuteReader() together :
using(var someNewReader = GetSelectReader(someSelectQuery, conn, transaction))
{
...
}
The thing is : this "someNewReader" object (or struct ?) should :
- somehow publish the same methods as
SqlDataReader - have a
.Dispose()method, which disposes of both the underlyingSqlCommandandSqlDataReader
What I tried
I tried creating a wrapper class, which holds two fields, a SqlCommand and a SqlDataReader, and :
- exposes the methods of the
SqlDataReader - reimplements a
.Dispose()method which disposes of the two objects (in the correct order)
Re-implementing .Dispose() in a correct maner (especially : handling exceptions the right way, and still try to .Dispose() of everyone) adds a coding overhead which is error prone, and yet would follow the exact smae structure for every .Dispose() chain.
Question
I was wondering if there was a mechanism to "chain together" several IDisposable objects, something that would allow me to describe :
- input :
objisDisposable - input :
parentisDisposable - output still have an
obj(with the same public interface, at least), but which correctly callsobj.Dispose()followed byparent.Dispose()on disposal