Cannot access a disposed context instance.
I'm receiving the
ObjectDisposedException
about a DbContext being disposed while using IDbContextFactory<>
to initialize my database context. After searching online for potential ways for me to approach resolving this, none of them seem to apply for my case.
Code:
-# Exception Trace is attached as .txt file.17 Replies
Hmm, you're using a pooled dbcontext from what I can read from the stacktrace
I suspect the disposal behaviour is connected to that
Maybe you can shrink the potential error area by trying a non pooled context first
Yeah I do have pooling toggled on for my database config
Here's after disabling pooling:
Found the trace differences just now
did you create a service scope?
Hm, interesting, looking at https://github.com/dotnet/efcore/blob/main/src/EFCore/Internal/DbContextLease.cs#L111 it does seem like the stacktrace you're going down would only happen for a context which does use pooling. The only way the DbContextLease does use an instance with a pool is from within a pooled factory https://github.com/dotnet/efcore/blob/main/src/EFCore/Infrastructure/PooledDbContextFactory.cs#L69
I'll go ahead and send how I'm injecting the dbcontext factory
Ohh I need to use
AddDbContextFactory<>()
insteadcan you register your responder with DI and ask for a SionDbContext in the constructor?
As in register the context?
Sion.Discord.Responders.GuildCreateResponder that one
That already is registered from another service
but registered as IResponder<Something>
Also, my error has been resolved by removing pooling
ok, cause i was looking at https://github.com/Remora/Remora.Discord/blob/main/Backend/Remora.Discord.Gateway/Services/ResponderDispatchService.cs#L303 and it creates a service scope and resolve responders, so accepting a SionDbContext in your constructor could work
GitHub
Remora.Discord/Backend/Remora.Discord.Gateway/Services/ResponderDis...
A data-oriented C# Discord library, focused on high-performance concurrency and robust design. - Remora/Remora.Discord
Not with a factory
no, there wouldn't be a need for factory in that case, it's more for apps that don't deal with service scopes
so the lifetime would be handled by the service scope remora creates, and it would be disposed when your responder return
Ah I see where you're coming from