简体   繁体   中英

ObjectContext instance has been disposed

I am using the entity framework the way described here: Entity framework uses a lot of memory

I realized I need to use "using" statement in order to work correct. When I am doing:

                using (IUnitOfWork uow = UnitOfWork.Current)
                {
                    CompanyRepository rep = new CompanyRepository();
                    m_AllAccounts = rep.GetQuery().
                        Select(x => new Account(x)).ToList(); ///HERE I GET THE EXCEPTION
                }

For this example, I getting:

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

What am I doing wrong?

I may be wrong, however the first that comes to my mind is that probably UnitOfWork.Current returns an already-disposed unit of work.

Imagine the following code:

void MethodA ()
{
    using (IUnitOfWork uow = UnitOfWork.Current)
    {
        // do some query here
    }
}

void MethodB ()
{
    using (IUnitOfWork uow = UnitOfWork.Current)
    {
        // do another query here
    }
}

MethodA (); // works OK
// now UnitOfWork.Current is disposed
MethodB ();  // raises exception

The question comes down to what exactly UnitOfWork.Current does and what is is supposed to do. Should it create a new object each time it is accessed? Should it keep a reference unless it is disposed? This is not obvious and you might have been confused by this.

Well, the error speaks for itself. After any of your **using** (IUnitOfWork uow = UnitOfWork.Current) your "global" context is disposed. So any attempt to access it will result in error.

I guess ObjectContext was disposed before you reached your using statement. Your linked question shows that you store context in HttpContext.Items or HashTable . If you wrapped all calls to UnitOfWork.Current by using only first block will work - all other will get disposed context from HttpContext or HashTable .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM