CommandAccesor does not expliclity close the IDataReader

Topics: Data Access Application Block
Jan 9, 2013 at 8:15 PM

I noticed in the Enterprise Library 5.0 code that the Execute method for the CommandAccessor does not use a using statement.

The ExcecuteReader method says the caller should close the reader.  I am concerned that if I use the CommandAccessor that I will end up with memory issues.

Do you think my concerns are valid?

        /// <summary>
        /// Executes the <paramref name="command"/> and returns an enumerable of <typeparamref name="TResult"/>.
        /// The enumerable returned by this method uses deferred loading to return the results.
        /// </summary>
        /// <param name="command">The command that will be executed.</param>
        /// <returns>An enumerable of <typeparamref name="TResult"/>.</returns>
        protected IEnumerable<TResult> Execute(DbCommand command)
            IDataReader reader = database.ExecuteReader(command);

            foreach (TResult result in resultSetMapper.MapSet(reader))
                yield return result;

Jan 9, 2013 at 10:03 PM
Edited Jan 9, 2013 at 10:27 PM

That's a good question; you are right to be concerned about closing of IDataReader's since not doing so causes a connection leak which can bring down an application.

The good news is that you don't have to worry.  The Execute method performs a yield return of the results from an IResultSetMapper MapSet method.  Enterprise Library provides a default implementation which looks like this:

private class DefaultResultSetMapper : IResultSetMapper<TResult>
    readonly IRowMapper<TResult> rowMapper;

    public DefaultResultSetMapper(IRowMapper<TResult> rowMapper)
        this.rowMapper = rowMapper;

    public IEnumerable<TResult> MapSet(IDataReader reader)
        using (reader)
            while (reader.Read())
                yield return rowMapper.MapRow(reader);

Notice that the MapSet method encloses the reader in a using block so that the reader will be Disposed (and the connection closed) when done.

Randy Levy
Enterprise Library support engineer
Support How-to 

Marked as answer by randylevy on 11/30/2013 at 6:02 PM
Jan 10, 2013 at 4:05 PM

Thank you Randy, this makes perfect sense :)