No need to dispose DataContext/ObjectContext in EF?

entity-framework idisposable repository repository-pattern

Question

Albahari writes in "c# 4.0 in a nutshell":

> Although DataContext/ObjectContext implement IDisposable, you can (in general) get away without disposing instances. Disposing forces the context’s connection to dispose—but this is usually unnecessary because L2S and EF close connections automatically whenever you finish retrieving results from a query <<

This feels wrong and FxCop also complains if you are not diposing something that is IDisposable.

I have the following repository code:

    public abstract class Repository<TEntity> : IRepository<TEntity> where TEntity : class
    { ...
        public void Add(TEntity entity)
    {
        using (var dbContext = this.UnityContainer.Resolve<DbContext>())
        {
            dbContext.Set<TEntity>().Add(entity);
            dbContext.SaveChanges();
        }
    }

    ...

    public virtual IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> expression)
    {
       using (var dbContext = this.UnityContainer.Resolve<DbContext>())
       {
           return dbContext.Set<TEntity>().Where(expression).ToList().AsEnumerable();
       }
    }
    ...

Note: I do not return IQueryable - lazy loading should not play a role. Resolve DbContext is configured as PerResolveLifetimeManager.

Is this approach OK or do I need to reconsider this based on Albaharis description?

1
10
5/31/2012 9:07:37 AM

Accepted Answer

You should always call dispose if class exposes it. The statement claims that EF and L2S close connection whenever they finish operation - as I know the statement is correct but in the same time ADO.NET team also closes connection in Dispose method so perhaps there are situations when connection is not closed.

7
5/31/2012 9:18:43 AM

Popular Answer

I'm working on EF 4.0 ObjectContext (yeah, I know...). I ended up looking at the code in DotPeek, and the dispose just nulls the reference to the connection and a few other things in the ObjectContext class.

When a connection is created (also found through DotPeek) it returns the existing instance. If the connection string is changed, it'll update the connection string for all instances.

That was my take on it at least. Need to look deeper but at first glance, it seems that you can get away with it.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow