Deepak Agarwal
Deepak Agarwal

Reputation: 468

Different contexts with InstancePerRequest using Autofac

I am using Autofac for DI in my project (web application). I have a LINQ expression which joins 2 different tables in the same DB something like this (All() is just a wrapper over dbSet.AsQueryable())

from repo1 in repository1.All()
join repo2 in repository2.All()
     on repo1.SomeField = repo2.SomeField
.....

I am registering my components (repo1 and repo2) in the container builder with InstancePerRequest().

When I execute my code, at the LINQ code, it throws be following error:" The specified LINQ expression contains references to queries that are associated with different contexts."

I thought the dbContext is shared (per request) across components registered via InstancePerRequest().

Thoughts?

Thanks!

Upvotes: 0

Views: 309

Answers (1)

Alexey Zimarev
Alexey Zimarev

Reputation: 19640

You do not show your "repository" constructor. If you want it to work properly, you need to register your DbContext with PerRequest as well and make your "repositories" get it injected as constructor parameter. Then it will just work. There is no implicit assumption that dependencies of components registered PerRequest should be instantiated with the same lifecycle. By default all components are registered per dependency.

Upvotes: 1

Related Questions