Question: How do you resolve the error below?
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.
Object name: 'Context Name'.'
Edit this Article
- Make sure that the function that is consuming the _context.ClassModal (Database Context) does not wrap the Database Context in a using directive. The using directive disposes the object every after use.
- Make sure that the function that is using the Database Context is not an Async function, an Async function that returns a Task runs in the background, this is a bad idea as the function will connect to the Database and run away with the active Database connection into a background worker thread, another instance call would then try to access the same connection to the Database but will not find the active connection because the first instance call has run away with it in the background.
- Make sure that your Interface and the Repository classes are registered as services.AddTransient this allows the instance instantiations to be active for an application session lifetime.
Call to Action: Leave a comment below if this solved your problem, you don't have to log in to leave a comment.