Question

I have ASP.NET MVC application that uses Entity Framework as ORM. Now I'm using PerWebRequest lifestyle for EF ObjectContext.

While profiling application performance under high load, I found a bottleneck in ObjectContext creation.

I want to change ObjectContext's lifestyle to Pooled, but there is an issue.

In legacy part of my application there is Service Locator anti-pattern. So the ObjectContext could be Resolved many times per web request, and not explicitly released after usage.

With PerWebRequest it's not an issue, because ObjectContext instance instantiated once and released guaranteed on EndRequest event.

With default Pooled lifestyle different ObjectContext instance would be returned for each Resolve method call. But I want to re use single instance in web request scope. Also I want the instance to release (return to pool) automatically at the end of request (with PerWebRequestLifestyleModule).

It seems to me, that I should implement custom LifestyleManager or custom IPool for Windsor. But I don't know how to combine Pooled and PerWebRequest lifestyles, because of lack of experience in Windsor.

Can you give me any ideas? Thanks.

UPD: About ObjectContext's state and reasons to reuse

There is performance reason. Creation of ObjectContext is quite expensive. I'm searching for ways to avoid it. I have two approaches to deal with ObjectContext's stateful nature and to reuse it:

  • use stateless context (with ChangeTracking turned off) for queries. For commands use another instance.
  • reset context's state on returning to pool.
Était-ce utile?

La solution

Don't reuse an ObjectContext across requests. You will leak shared state between requests (and potentially between users). The ObjectContext class is not designed to be reused.

In your question I did not find a reason not to use PerWebRequest, so just use that.

Autres conseils

In your case, you could change the lifestyle to be tied to the current thread, ensuring that each worker thread in the web app gets an instance

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top