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 DataReader
itself 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.
Holding the database connection as a member variable in your reader class and making your reader class implement IDisposable seems fine to me.
However, you might consider making your method return IEnumerable and using yield return
statements to walk through the data reader. That way you can return the results and still clean up from within your method.
Here's a rough sketch of what I mean:
public IEnumerable<Person> ReadPeople(string name)
{
using (var reader = OpenReader(...))
{
// loop through the reader and create Person objects
for ...
{
var person = new Person();
...
yield return person;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With