Home > DeveloperSection > Forums > How to dispose the context variable in c#?
Tanuj Kumar

Total Post:134

Posted on    January-22-2014 11:36 PM

 C# C# 

 1 Reply(s)
 1455  View(s)
Rate this:

I want to dispose the devDB context object in the below code.

private static void InitContainer()


     var devDB = new TestContext(constr); 



                    .RegisterInstance<IRepository<User>>(new Repository<User>(devDB))


private static void CleanUp()


    if (Container != null)





I tried a using statement, but the I receive the following error:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

How can I dispose devDB correctly?

Pravesh Singh

Total Post:412

Posted on    January-23-2014 12:51 AM

Hi Tanuj,

Use using statements:

using(var devDB = new TestContext(constr))


    // rest of your code


It will automatically Dispose your variable if it's Disposable.

Don't want to miss updates? Please click the below button!

Follow MindStick