public void Dispose() { if (_savedContextData.Disposed) { //too late to throw error. return; } if (!_isParentScope) { _savedContextData = null; return; } var contextData = CallContextContextData.GetContextData(); if (contextData != _savedContextData) { //Duplicate contextdata has been created by someother thread. Could be result of two thread trying to create contextData at same time. throw new Exception( "Context disposed or duplicate context seen. Something went terribly wrong in the programming. Please check your code to correct."); } if (_isParentScope) { if (!_isCompleted && _mode == DbContextOption.Mode.Write) { //Cleaning as much as possible. If DbContext is getting disposed before transaction is completed // atleast rollback all uncommitted transaction. _savedContextData.Rollback(); } contextData.Dispose(); //Remove the contextData from the CallContext. CallContextContextData.RemoveContextData(); contextData.Disposed = true; Debug.WriteLine("DbContext disposed successfully"); } }