David Stocking
David Stocking

Reputation: 1212

Multiple entity framework DbContext still leads to concurrent exception

So, I am basically trying to make it so that I can run multiple tasks that each task has its own DbContext so that they don't cause an exception. So basically, like how ASP.NET async handlers work. Right now I'm do something to the effect of

// set up the unity container
// WON'T WORK the dbUnitOfWork will used in two tasks.
container.RegisterType<Framework.Data.IDbUnitOfWork, Framework.Data.EntityFramework.DbUnitOfWork>(Core.IoC.Lifetime.PerThread);
container.RegisterFactory<System.Data.Entity.DbContext, ContextFactory>(o => o.Create, Framework.Core.IoC.Lifetime.Transient);



AsyncContext.Run(() => app.Run());
// run the following code fragment with an Async Context from Nito



workers.AddRange(container.resolveAll<IWorker>());
foreach (var worker in workers) {
    tasks.add(worker.WorkAsync());
}
Tasks.WhenAll(tasks);

but what happens is that every time I keep getting this cursed "NotSupportedException" because of a second operation started on the same DbContext. I tried making my DbContext be PerThread in Unity, but that still didn't seem to work. The way I pulled of per thread (well hoping at least) is

Tasks.Run(() => worker.WorkAsync());

I just want to be able to run a group of tasks each with their own DbContext. So that they can all asynchronously do independent database operations. So how do I pull off this desired behavior.

Upvotes: 0

Views: 550

Answers (1)

DixonD
DixonD

Reputation: 6628

Based on your comments, I have an idea that the cause of the issue might be that you defined PerThread lifetime of IDbUnitOfWork and injected it in the following line of code:

workers.AddRange(container.resolveAll<IWorker>());

So, you inject IDbUnitOfWork in the same main thread, and that's why you get the same instance.

Upvotes: 1

Related Questions