ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application

Question: How do you solve for the error in AspNet 6 MVC using C# that says "ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing of a context instance 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 instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing of context instances. Object name: 'DatabaseContext'."

 

Answer: There is a chance that you are trying to access a disposed of an object, the cause of this error might be that you are trying to access an Interface injected into a Repository Class through a View Component. Remember, when you call a function from a Service class via a ViewComponent code behind, the Dependencies in that Service Class (Repository Class) do not (based on my experience) instantiated or get injected into the Service. 

In short, make sure that the View Component requests resources/data from a Controller, this way all the dependencies will be injected again into the Dependency Injection Container.

Let me know if this helped you or if you solved it by using another method. You can leave a comment without login in if you want.


Edit this Article
ObjectDisposedException: Cannot access a disposed context instance ebook e-book AspNet 6 C-Sharp MVC .NET 6 published
Was this page helpful?
Yes Yes! this solution to the problem was helpful. No No! this solution to the problem was not helpful.. Leave ErnesTech Feedback.Feedback
If you log in, you will be notified when someone leaves a comment.

Other users would like to know if this solution helped you.

Your Session is Ending
Login to Continue

© 2021 - ErnesTech - Privacy