The Scope being disposed is not the Ambient Scope

Hello,

I am on Umbraco v12.1.1
I am trying to create content programmatically, I was able to do it for one culture but I would also like to create the same content for all cultures (for now)

Please keep in mind I have no Tasks or Async code, this is all synchronous

The behaviour is unexpected, it usually breaks for the 2nd culture and 50% of the documents.

Code snippet

private IContent? AddOrUpdateCategoryNode(CategoryDto category, IContent parentNode, string brandDocId)
{
    try
    {
        IContent? newNode = _contentService.Create(category.Name, parentNode.Id, Application.ModelTypeAlias);
        string imagesBlock = string.Empty;
        imagesBlock = BlockListFactory.Create(_contentTypeService, category.Images, image => new Dictionary<string, string>() {
                {"imageUrl", image.Url},
                {"imageAltText", image.Alt}
        }, ProductImageItem.ModelTypeAlias).ToString();

        foreach (var culture in cultures)
        {
            newNode.SetCultureName(category.Name, culture);
           
            newNode.SetValue("brands", string.Join(",", brandDocId), culture);
            if (!string.IsNullOrEmpty(imagesBlock)) newNode.SetValue("images", imagesBlock.ToString(), culture);
            
            _contentService.SaveAndPublish(newNode,culture);
        }

        return newNode;
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, $"Error while creating node for category {category.Name}.");
        return null;
    }
}

It breaks when it hits SaveAndPublish()

Exception trace

{“The Scope 5f2261f0-8e97-4e8c-a540-0d69949895e8 being disposed is not the Ambient Scope 477ed48a-1c75-4be4-b607-7b9f5d020aea. This typically indicates that a child Scope was not disposed, or flowed to a child thread that was not awaited, or concurrent threads are accessing the same Scope (Ambient context) which is not supported. If using Task.Run (or similar) as a fire and forget tasks or to run threads in parallel you must suppress execution context flow with ExecutionContext.SuppressFlow() and ExecutionContext.RestoreFlow().”}

What I have tried:

  1. Creating a scope using both IScopeProvider and ICoreScopeProvider (and placing it inside the foreach, outside the foreach as well as outside the whole function)
  2. Using ExecutionContext.SuppressFlow(), this just results in freezing SaveAndPublish() - I have also tried placing it everywhere, no luck
  3. Setting the values then using SaveAndPublish() with a wildcard culture
  4. Not setting the culture name

I have tried many more things but no luck, couldn’t find much information on it. Am I setting the values for multiculture incorrectly or is it a bug?


This is a companion discussion topic for the original entry at https://our.umbraco.com/forum/113065-the-scope-being-disposed-is-not-the-ambient-scope