FusionCache: [BUG] Possible bug. FusionCache + EntityFramework (latest) on ASP NET Core 8 (.NET 8)

Hi, I’m using the following code as suggested in the documentation, database is Azure SQL, FusionCache configuration provided here: #210

var data = await _cache.GetOrSetAsync("someKey-"+someId, async (cancellationToken) =>
    {
        var records = await dbContext.Table
            .AsNoTracking()
            .Where(x => x.Id == someId)
            .FirstOrDefaultAsync(cancellationToken: cancellationToken)
            .ConfigureAwait(false);
        if (records== null)
        {
            throw new RecordNotFoundException();
        }
        return records ;
    })
    .ConfigureAwait(false);

And sometimes, I’m getting strange exception:

System.InvalidOperationException: A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.

   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()

I tried to change DbContext lifetime to Transient, but it didn’t help. It does not happen always. Did you face with similar?

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 16

Most upvoted comments

Just a suggestion, maybe it is not correct from any point of view, but what if L2 operation that could be done separately do as a background process? I understand that it is probably not straightforward to implement, but just an idea.

You already can, just set AllowBackgroundDistributedCacheOperations to true and you’re done. Also, any potential issue with the distributed cache will be automatically handled by Auto-Recovery.

Hope this helps.

@jodydonetti It has been 4 days already passed, and still no such errors. So, I suppose IDbContextFactory should be recommended in documentation. Since .NET 7/8 it could be easily added to DI together with DbContext. So, both could be used at the same time. factory - for cache-inside blocks wrapped into “using”, and DbContext for normal operations.

The latest one. I switched this morning to IDbContextFactory<TContext> and now creating DbContext inside GetOrSetAsync block - so far so good. Will monitor more