Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No need to dispose DataContext/ObjectContext in EF?

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?

like image 760
Volker von Einem Avatar asked May 31 '12 09:05

Volker von Einem


1 Answers

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.

like image 95
Ladislav Mrnka Avatar answered Oct 20 '22 03:10

Ladislav Mrnka