IDisposable implementation for entity framework DbContext RRS feed

  • Question

  • User46076047 posted

    I have a private field that holds instance of dbContext in my class that i am initialize in the class constructor.  
    I would like to implement IDisposable interface on that class so it will execute dbContext.dispose when disposing.

    I am not sure if i need to do something in ~BaseDal() and in Dispose() function.

    In other words, if i am using  dbContext.Dispose() in my Dispose(bool disposing) function. is means i am releasing only manage code or also unmanage code?

    public class BaseDal:IDisposable
            private MyDbContext _dbContext;
                _dbContext = new JungleDbContext();
            public DbRawSqlQuery<TElement> ExecuteSP<TElement>(string spName, params object[] parameters)
                    return _dbContext.Database.SqlQuery<TElement>(spName, parameters);                        
            #region IDisposable Support
            private bool disposedValue = false; // To detect redundant calls
            protected virtual void Dispose(bool disposing)
                if (!disposedValue)
                    if (disposing)
                    // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                    // TODO: set large fields to null.
                    disposedValue = true;
            // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
            // ~BaseDal() {
            //   // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
            //   Dispose(false);
            // }
            // This code added to correctly implement the disposable pattern.
            public void Dispose()
                // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
                // TODO: uncomment the following line if the finalizer is overridden above.
                // GC.SuppressFinalize(this);
    Wednesday, November 29, 2017 11:56 AM

All replies