My method which calls SQL Server returns a DataReader but because of what I need to do – which is return the DataReader to the calling method which resides in a page code-behind – I can’t close the connection in the class of the method which calls SQL server. Due to this, I have no finally or using blocks.
Is the correct way of disposing resources to make the class implement IDisposable? Alternatively should I explicitly dispose the unmanaged resource (class-level fields) from the caller?
EDIT: I send the datareader back because I need to bind specific data from the datareader to a listitem control, so in the calling class (Codebehind page), I do:
new ListItem(datareader["dc"]); (along those lines).
I would say yes, implement
IDisposable. One of the main reasons as far as I can tell to use it is when you cannot trust the user of the object enough to do it properly themselves. This seems to be a prime candidate for that.This being said however, there is a question to your architecture. Why is it that you want to send the
DataReaderitself to the page instead of calling a method to do it for you (including the relevant cleanup) by returning what is necessary? If it necessary to give the actual reader to the page, then so be it.