Is it mandatory for DbContext to be injected .InPe

2019-07-04 03:52发布

问题:

I have been using Ninject IoC container in my ASP.NET MVC3 portal. Whenever I've been injecting Entity Framework DbContext in PerThread scope, my data wasn't consistent, changes would not get displayd for some time after I've made changes to Entities, etc.

After I've switched the IoC configuration to resolve a fresh copy of my DbContext instance for each request (PerRequestScope()), all the problems were gone.

So is it absolutely mandatory to use PerRequest injection strategy in MVC3 applications?

回答1:

Yes, it is mandatory.

Your problem works like this:

  • Thread A loads an entity
  • Thread B modifies that entity
  • The next request to Thread A uses the cached entity from the first request, ignoring the changes