0

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?

1

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I did integrate topshelf's Api in a sample Console application, it works just fine, but when i implemented in my actual Asp.NET MVC app, jobs did't ran and in output window i see some exception that says Service was properly configured and it's telling me there's something wrong with applicationhost file located in main web Project under .vs directory any solution?
I was able to get it working for by registering a module builder.RegisterModule(new QuartzAutofacFactoryModule());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.