EntityFramework Core Migration (Code First) — Part III: Autofac DI and Async DbContext Handling

Chewy2Theo
2 min readMay 29, 2021

--

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.

Sources
https://stackoverflow.com/questions/48767910/entity-framework-core-a-second-operation-started-on-this-context-before-a-previ

This article is a part of the .Net to .Net Core Migration Series
https://theochiu2010.medium.com/net-to-net-core-migration-2eb31584f95c

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Chewy2Theo
Chewy2Theo

Written by Chewy2Theo

Just another developer who's into lazy tools that can make my life easier, and hopefully yours too.

No responses yet

Write a response