c# - Entity Framework Object Context per request in ASP.NET? -
is considered practice use single objectcontext per request? read these objects should short lived , not extremely costly instantiate make case appealing 1 of them per request? if yes, there patterns implement this?
yes accepted approach have objectcontext/dbcontext lifetimes per httprequest. here's sample have provided in answer.
hoewever, it's better leave these lifetime managements ioc library. famous ones castle windsor, autofac.
update:
dispose context, can use application_endrequest
method in global.asax. following code not tested you'll idea:
protected virtual void application_endrequest() { var key = "mydb_" + httpcontext.current.gethashcode().tostring("x") + thread.currentcontext.contextid.tostring(); var context = httpcontext.current.items[key] mydbcontext; if (context != null) { context.dispose(); } }
Comments
Post a Comment