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?
CodePudding user response:
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.
CodePudding user response:
The problem was solved by deleting the "using" and keeping the content //doing something here.