How should I use the Entity Framework DbContext dependency nesting in a web application? (InstancePerHttpRequest vs SingleInstance)

I read that the DbContext object should be created as an instance of InstancePerHttpRequest, and not SingleInstance, because of its unsafe nature, and it may consume too many resources between the details that do this. But I use repository objects that use an instance of DbContext. Should I make them InstancePerHttpRequest or make them SingleInstance and use DependencyResolver to get the current DbContext.

What would be the best object creation design for Autofac (or any other DI), DbContext, Repository, and Service web applications?

Another question: how expensive is it to create another DbContext object for each repository or service for each web request (for example, 10-15 of them in the request)?

+5
source share
3 answers

DbContext is incredibly cheap to create an instance, so I wouldn't worry too much about the time taken to get a new one.

The problem that I am encountering in the field of DbContext is not so much protecting the threads from query isolation. Since anyone can cause changes to be saved and transfer the entire graph of the object to the database, you want to make sure that you call it only in the context of your specific changes.

DbContext , , . , singleton, . ( , )

- - , HttpRequest. , , , , , .

, , , autofac, :)

+7

DbContext - SingleInstance. . UoW, . , .

+1

DbContext is cheap to instantiate, so I would design it so that each service gets its own instance. 10-15 for each request is in order, if you do not have a problem, you can return to the number of DbContext instances created. Anything else smells of early optimization for me.

I tried to remain DI agnostic, since I mainly use StructureMap.

0
source

All Articles