HOW TO DISPOSE THE CONTEXT VARIABLE IN C#?

Tanuj Kumar

Total Post:134

Points:940
Posted by  Tanuj Kumar
C# 
C#
 1483  View(s)
Ratings:
Rate this:

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

private static void InitContainer()

{

     var devDB = new TestContext(constr); 

                 Container                

                    .RegisterInstance<TestContext>(devDB)

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

}

private static void CleanUp()

{

    if (Container != null)

    {

        Container.Dispose();

    }

}

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?

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: How to dispose the context variable in c#?

    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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!