简体   繁体   中英

Error "The operation cannot be completed because the DbContext has been disposed."

I'm trying to get profiles from database using EntityFramework.

But every time I am getting the following error:

The operation cannot be completed because the DbContext has been disposed.

My code:

private readonly IDbContextDMO _globalContext;

using (IProfilService profilService = _profilService ?? new ProfilService(Settings, _globalContext))
{
      //doing something here
}
var r_GetHigherProfileAsync = await _profilService.GetHigherProfileByIntervenantIdAsync();

I can't understand why I am getting this error. Can anyone help me please?

You are using the ProfilService , which means as soon as "doing something here" completes, Dispose() is called, which disposes _globalContext (from the comment).

You should consider your intended lifetimes. If the db-context is intended to outlive any single ProfilService , then ProfilService should not be disposing it (or should at least have a flag to control that).

Similarly, if _profilService is not null, you'll currently be disposing it even though it isn't obvious that it should now die; so perhaps:

var profilService = _profilService;
bool disposeSvc = false;
try {
    if (profilService is null)
    {    // temporary just for this call
         profilService = new ProfilService(Settings, _globalContext);
         disposeSvc = true;
    }
    //doing something here
} finally {
    if (disposeSvc) profilService?.Dispose();
}

Alternatively and much more simply: use more transient lifetimes, rather than keeping things globally. Then you can usually dispose readily.

The problem was solved by deleting the "using" and keeping the content //doing something here.

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