Where should I keep my context instance in asp.net website?
I'm building an asp website and using Entity framework as ORM.
Where should I put my entity frame work instance ?
currently in every controller i have a private member that looks like this :
MyDBEntities mDbContext = new MyDBEntities();
This means that on every request, a new controller is created which in turn creates a new mDbContext . Moreove开发者_如何学Pythonr, I have mDbContext
in the membership provider (to check if the user is a member) and in the role provider(to check his role) and in some binders(to get some data which the view cant supply), meaning I might create 3-4 connections to the db for every page request?
I'm probably doing something wrong, but what is the right way to do it?
As for the controllers this is perfectly OK. Many IoC examples with MVC recommend constructor injection of a context into an MVC controller, which is nearly the same.
One context instance in the membership/role providers is not a good idea because they are singletons. Sooner or later the context will get addressed by multiple threads. You should have a context per method call there.
More details here: What could cause many data access exceptions using EF code first in a custom RoleProvider?.
put your database logic in a database class (for example a repository).
in that repository, you can have multiple methods (getallcustomers
, savecustomer
etc.) which all create a new MyDBEntities
object, with a using
statement:
using (MyDBEntities mDbContext = new MyDBEntities())
{
//your db code here
}
as i understand creating the MyDBEntities
object is not more than creating a new connection in ADO.Net so it's a lightweight operation.
you can call the repository methods from your controller.
if you seem to use a method quite often from a controller (ie multiple times per request), you might consider caching.
Follow the Unit Of Work
pattern, a demo web app here.
精彩评论