https://discord.umbraco.com logo
#help-with-umbraco
The Scope being disposed is not the Ambient Scope (custom tables)
# help-with-umbraco
o

Owain Jones

10/11/2023, 11:36 AM
Hi all, I have a repository pattern set up for some custom database tables, here's the Update method:
Copy code
csharp
public virtual async Task<TOut> Update(TOut item)
{
  using var scope = _scopeProvider.CreateScope();
  using (var transaction = scope.Database.GetTransaction())
  {
    var poco = _mapper.Map<T>(item);
    await scope.Database.UpdateAsync(poco);
    transaction.Complete();
    item = _mapper.Map<TOut>(poco);
  }
  scope.Complete();
  return item;
}
The above class is registered as transient. If I call this method multiple times in one request (e.g. in a foreach loop), then I seem to run into this exception:
The Scope being disposed {guid} is not the Ambient Scope {guid}
and all subsequent attempts to run the method result in
No AmbientContext was found.
exceptions; only a restart fixes it until it happens again. The addition of a
Thread.Sleep(500);
to the start of the Update method seems to completely fix the issue. But that's a gross band aid fix which only masks whatever the underlying issue is. (feels like the first scope is not being closed in time and the second scope is created as a child scope?) has anyone ran into this before? Am I missing something stupidly obvious?
h

huwred

10/11/2023, 12:00 PM
I had a similar issue but it was due to a nested call, to get around it I had to declare them as autocomplete in the constructor and then just do a transaction complete, don't know if that will help
o

Owain Jones

10/11/2023, 6:14 PM
Cheers Huw, I'll have a go at using the autocomplete option tomorrow 🙂