private ShipHubContext _ephemeralContext; // this is for WithContext only. If you're not WithContext, don't use it. private async Task WithContext(Func <ShipHubContext, Task> dbWork) { if (_borrowedContext != null) { // legacy path await dbWork(_borrowedContext); } else if (_ephemeralContext != null) { // re-entrant path await dbWork(_ephemeralContext); } else { try { _ephemeralContext = _contextFactory.CreateInstance(); await dbWork(_ephemeralContext); } finally { if (_ephemeralContext != null) { _ephemeralContext.Dispose(); _ephemeralContext = null; } } } }