Search code examples
c#enterprise-libraryidatareader

C# Reader Disposal Review


I am using the Enteprise Library to query my database. When I run a query, I am relying on stored procedures. Currently, I am using code that looks like the following:

Database database = DatabaseFactory.CreateDatabase();
DbCommand command = database.GetStoredProcCommand("MyStoredProcedureName");

database.AddInParameter(command, "filter", DbType.String, filter);

Result result = null;
using (IDataReader reader = database.ExecuteReader(command))
{
  if (reader.Read())
    result = new Result(reader);
}
return result;

How can I be sure that my reader is being closed? I have noticed that my application sometimes fails to load on subsequent loads. I suspect that something is being left open. But I can't figure out how to track it down.

Based on the code shown above, shouldn't teh reader get closed and disposed because of the 'using'?

Thank you!


Solution

  • The reader is guaranteed to be closed, since it is wrapped in using. However, the DbCommand also implements IDisposable and there's no using/dispose call for it.

    Database database = DatabaseFactory.CreateDatabase();
    using(DbCommand command = database.GetStoredProcCommand("MyStoredProcedureName"))
    {
        //snip (no change)
    }
    return result;
    

    The reader doesn't represent the underlying connection, just the buffer for reading the response.