views:

75

answers:

3

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?

A: 

The garbage collection will dispose of the object when it goes out of scope. So your code will work, but this is not the best solution.

It would be better to place the creation of the database object in a using statement.

Shiraz Bhaiji
+2  A: 

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.

erikkallen
+2  A: 

I know this is ancient history, but I can't leave these answers be.

You do not need to dispose Database instances. It doesn't even implement IDisposable.

You do need to dispose explicit DbCommand objects that you've created.

Chris Tavares