问题
I have read that DbContext object should be created as InstancePerHttpRequest, not SingleInstance, because of its thread-unsafe nature and it might consume too much resource between requets which makes sence. But I am using Repository objects which uses DbContext instance. Should I make them InstancePerHttpRequest or make them SingleInstance and use DependencyResolver to get the current DbContext.
What would the best object creation design be, for Autofac (or any other DI), DbContext, Repository and Service based Web application?
Another question, how expensive it is to create a different DbContext object for each repository or service for each web request (like 10-15 of them in a request)?
回答1:
DbContext is incredibly cheap to instantiate so I wouldn't worry too much around the time taken to get a new one.
The issue I have with scoping around DbContext isn't so much thread safety its query isolation. Because anyone can call save changes and commit the whole object graph to the database you want to make sure you only call it on a context with your specific changes.
Another key thing to understand about DbContext is that performance degrades the more items it is tracking. This means if you bind it in singleton you can cause some pretty serious performance issues. (there are ways around this but its really good to be aware of see my post on this here)
My personal preference for web apps is to bind both your context and repository in the scope of an HttpRequest. This means that only your current request thread will be able to save changes, and it also limits the amount of items you are likely to track.
Sorry a bit of my terminology probably doesn't match autofac as im a ninject man myself :)
回答2:
DbContext is your Unit of Work, and is thus never suited for SingleInstance scope. Treat it as such. Sometimes a request maps directly to a UoW, but not necessarily always. Consider this before you scope it to the request.
回答3:
DbContext is cheap to instantiate, so I would design it such that each service gets its own instance. 10-15 per request is fine, unless you encounter a problem you can trace back to the number of DbContexts instantiated. Anything else smells like pre-mature optimization to me.
I tried to stay DI agnostic, as I primarily use StructureMap.
来源:https://stackoverflow.com/questions/12207424/how-should-i-scope-dependency-injection-of-entity-framework-dbcontext-in-a-web-a