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:

  1. a new dbcontext in each method.
  2. a new dbcontext per object (class member).
  3. 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

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -