Search code examples
.netenterprise-librarydispose

Explicit closing required?


I am using EntLib 4.1.

_db = DatabaseFactory.CreateDatabase("DbName");
DbCommand dbCommand = _db.GetStoredProcCommand("someProcedure");
_db.AddInParameter(dbCommand, "Id", DbType.Int32, id);
result = _db.ExecuteNonQuery(dbCommand);

After performing the task do I need to dispose the _db object, like:

finally
{
    _db = null;
}

... or will EntLib Framework handle it automatically?


Solution

  • doing _db = null does NOT dispose the object.

    You have to do _db.Dispose(), or use a using block.

    Garbage collection will dispose the object at a non-deterministic time, but as soon as you create an object implementing IDisposable, you should make sure you ALWAYS call Dispose() (unless, of course, you give it away to an object or another function which promises to do it).

    In this case, it is easy to see that there is no way for the factory to know when you're done with the object, so you have to dispose it yourself.