简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM