EntityFramework Core Migration (Code First) — Part III: Autofac DI and Async DbContext Handling
If you’re getting the below error then you’re probably at the right place for a solution.
A second operation started on this context before a previous operation completed
So back in the old days when I configured the DI for the DbContext I could do the following:
builder.RegisterType<WebBaseEntityContext>()
.AsSelf()
.InstancePerRequest();
What the above means is whenever a http request comes in, a new instance will be instantiated. But according to the official Autofac documentation, things are now different with .Net Core
there’s no special “request level scope” anymore. Instead of registering your dependencies InstancePerRequest, use InstancePerLifetimeScope and you should get the same behavior.
So it says “you should get the same behavior”.. but it was not quite the case. I spent a lot of time on this issue because EF Core kept using the same DbContext for all the requests and things started going crazy when multiple requests were coming in.
So after loads of research and testing I have come up with the below configurations to resurrect the magic.
First register the DbContext as Transient in your startup.cs ConfigureServices method.
services.AddDbContext<WebBaseEntityContext>(options =>
options.UseSqlServer(“XXX DB Connection String”),
ServiceLifetime.Transient);
Supposedly this should tell the DI to give you a new instance every time a new http request comes through. However my Unit of Work class still uses the same instance of DbContext somehow. So this is what I added on top of the above transient configuration.
_dbEntity = _serviceProvider.GetRequiredService<WebBaseEntityContext>();
Before I call SaveChanges I would request for a new instance from the DI pool. So with the two combined configurations above the issue was resolved.
This article is a part of the .Net to .Net Core Migration Series
https://theochiu2010.medium.com/net-to-net-core-migration-2eb31584f95c