asp.net mvc - When/How to dispose DbContext when returning IQueryable? -
i've started using iqueryable inspired http://www.codethinked.com/keep-your-iqueryable-in-check. i've been used doing in repos:
public ienumerable<poco> getbyid(int id) { using (var ctx = new dbcontext()) { var query = ...; return query.tolist(); } }
now i'm doing instead:
public ipageable<poco> getbyid(int id) { var ctx = new dbcontext() var query = ...; return new pageable(query); }
but i'm wondering if best way handle new dbcontext()
. better place dbcontext
class member
public class repo { private dbcontext _ctx = new dbcontext(); }
or injection it
public class repo { private dbcontext _ctx; public repo(dbcontext ctx) { _ctx = ctx; } }
what pros , cons to:
- a
new dbcontext
in each method. - a
new dbcontext
per object (class member). - injecting
dbcontext
.
i'm using ninject can use .inrequestscope();
(if should effect answer)
a couple other questions:
- should repo implement idisposable if dbcontext kept class member?
- is there better way handle disposal of dbcontext above?
i go injecting dbcontext, inrequestscope
. gives benefits of dependency injection.ninject dispose dbcontext on end of cycle dbcontext implements idisposable. see thread
if use di, other 2 questions become irrelevant.
Comments
Post a Comment