I have a method ("GetDataReader," let's call it) that returns a SqlDataReader. It's inside a Singleton DataFactory class that maintains a persistent connection to the database.
The problem with this is that after being returned, the DataReader is still "connected" to the Connection object in my DataFactory. So, I have to make sure the code that calls GetDataReader then calls Close() on the DataReader that comes back, otherwise, it "locks" the Connection with this:
There is already an open DataReader associated with this Command which must be closed first.
How can I "detach" the DataReader before I send it back from GetDataReader? Either that, or clone it and send back the clone? I don't want to have to make the calling code always explicitly close it.
There has to be a best practice here.
Update:
Thanks everyone for your input. The bottom line is that I need to lose the habit of using DataReaders and switch to DataTables. They're much more manageable.
Also, thanks for the note on connection pooling. I knew about it, but just didn't put two and two together and realize I was re-inventing the wheel.