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'."

 


Login to See the Rest of the Answer

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.





Jack said:

I have seen this error happen when using Asp.Net Role Manager from a Service Repository, no matter what I try whether to obtain the Service from a Service Provider or obtain it via Dependency Injection. The error still occurs, I mean how do you avoid this error?

Posted On: February 20, 2022 13:46:47 PM

© 2024 - ErnesTech - Privacy
E-Commerce Return Policy