3
     public class AccountController : Controller
     {

        private readonly mydbcontext db = new mydbcontext();

        protected override void Dispose(bool disposing)
        {
          if (db != null)
           {
              db.Dispose();
           }
           base.Dispose(disposing);
         }


        public ActionResult Login()
            {
               var result = db.User.Select(x=>x);
// Do i need to call db.Dispose here? or will it get dispose automatically?
                return View(result );
            }              
      }

I'm using the object of mydbcontext db here to get user's list.
Do i need to call db.dispose explicitly or using statement inside my login action result or will it dispose the object of mydbcontext automatically.

rohit singh
  • 550
  • 1
  • 11
  • 32
  • I would use "using" in the Controller and also have a kind of repository with which you can control the lifetime on your DbContext. If you have the db on class level you need to implement IDisposable and dispose resources there !!! But if you use using it will automatically be disposed – Legends Apr 17 '15 at 07:55
  • I'm having some unmanaged memory leakage, so i'm trying to study the same. Do i need to call db.dispose here? – rohit singh Apr 17 '15 at 07:57
  • As a general rule, you should dispose all `IDisposable` members of an object instance in its `Dispose` method. – ken2k Apr 17 '15 at 08:04

1 Answers1

-1

db will be disposed, when AuctionController will be disposed. You don't have to do more than that.

But better solution to use DependancyInjection. Like that

Community
  • 1
  • 1
Szer
  • 3,426
  • 3
  • 16
  • 36
  • 1
    he does not use DI and he has to dispose dbcontext therefore! All components that implement IDisposable should be registered with the HierarchicalLifetimeManager to ensure that they are properly disposed at the end of the request. – Legends Apr 17 '15 at 08:20
  • Is it a good way to write dbcontext = new dbcontext at the first line or we should explicitly call dbcontext inside action results? – rohit singh Apr 17 '15 at 08:45
  • In your case I would explicitly call it in the method and not globally, but always in as using block. – Legends Apr 17 '15 at 21:05