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
You already can, just set
AllowBackgroundDistributedCacheOperationstotrueand 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