I’m using MVC + Entity Framework 5 and currently looking at the Unit of Work pattern. In a controller class I see the following code:
private UnitOfWork unitOfWork = new UnitOfWork();
Does this mean that for every controller the UnitOfWork class is created, resulting in a database connection per UnitOfWork instance? Or do all DbContext instances (in this article SchoolContext instances which are created in UnitOfWork) share the same connection?
My second question: would it improve the performance of the application when only one UnitOfWork instance is created which is stored in the HttpContext, or is there a better approach?
First, let me caution you. I know you aren’t doing this, but I want to make sure you understand that you should never ever ever create a single data context and make it a static or singleton. The reason is that statics are shared between all instances of the app (ie multiple users) and data contexts are not multi-thread or multi-user safe.
Having given that warning, let’s move on.
In general, you don’t have to worry about this. The reason is that even though you create multiple UnitOfWorks, only one controller will ever be active at a time (per web request). Entity Framework has a connection pooler that reuses connections and optimizes their use. (actually, this is part of Ado.net, but it still applies)