Aarif
Aarif

Reputation: 1675

Entity Framework : how to work with multiple instances of DbContext across multiple threads

I'm using Autofac to inject the dependencies, my application needs to work on the backend, I'm using Quartz to trigger background workers.

I use the following code:

builder.RegisterType<AppContext>()
               .AsSelf().InstancePerDependency()

allowing every worker process (thread) to have a new instance of the DbContext class, I'm doing this because the DbContext class is not thread safe.

The real problem starts when I go to update or create something it says

Object was not found in the ObjectStateManager

I've seen some solutions for that like detaching and attaching the entity. But in my case, my repository methods are being used by the frontend (Asp.Net MVC). and I don't want to replicate those methods, one specific for DB call from the web app and one from background worker.

Any solution?

Upvotes: 0

Views: 2042

Answers (1)

Akos Nagy
Akos Nagy

Reputation: 4350

Using InstancePerDependency(), Autofac will create one DbContext not just for every worker, but every time when an object being created needs one. Assuming that you use 3 repositories and they each have a context constructor parameter, this means three different contexts (not to mention the fact that you have to manage disposal yourself and you probably would like to create one context per web request as well, which this does not allow you to do).

What you need is this Autofac-Quartz integration package:

https://github.com/alphacloud/Autofac.Extras.Quartz

As per the documentation, this creates a lifetime scope for every job. So if you register your context as InstancePerLifetimeScope(), everything inside one job (which has its own lifetime scope) gets the same context object. That might solve your problem.

Upvotes: 3

Related Questions