My project got a Exception :
System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
I searched for the answer but all I got is use AddScoped
or AddTransient
instead of AddSingleton
. But in my code, It's AddScoped
already.
Then, I tracking the creation and dispose by adding this code to constructor and Dispose method.
Constructor:
crrGuid = Guid.NewGuid(); //this is a field I added to tracking
Console.WriteLine("Created: " + crrGuid.ToString());
Dispose Method:
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
Console.WriteLine("Disponsing :" + crrGuid.ToString());
}
And this is the console I got after perform 2 request. The first, It's works, I can fetch my data. But the second request is not, It thrown exception even my Dispose method is not called yet (see the last line of console screenshot):
I got this exception only with some Entity/Table, others work fine.
PS: My code is too much, I don't know what should be share. Please comment, If I could public it, I will edit my post
Edit 1: Add constructor and Dispose method actually in my DBContext
public Context([NotNull]DbContextOptions options) : base(options)
{
Guid = Guid.NewGuid();
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Create DbContext:" + Guid);
Console.ResetColor();
}
public override void Dispose()
{
base.Dispose();
Console.WriteLine("Dispose DbContext:" + Guid);
}
Proposed duplicate
I have read the proposed duplicate and I think my case is different because I found the cause. The cause is in my conversion in my DBContext. The answer in linked topic definitely not helped me anything in solving this.