Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

Object disposed exception

In my last two projects I've been experiencing an object disposition exception that I didn't know how to resolve. Let me explain deeper. From my controller class, I have to call a method that belongs to another project and it's accessed via reference. This method simply queries some objects via entity framework and the context is accessed with using (to dispose later the object).

The problem is that when I try to access the object from the controller, some references to other objects have been disposed and I cannot access the data from the controller (because it is disposed). But I need to access this data from the controller and not from the referenced class that disposes the object.

My solution is always to remove the using and not dispose the object, but I know that this is not a good solution and it has to exist another method to do it.

Could you help me?

Thanks, great course so far.

1 Answer

Steven Parker
Steven Parker
231,122 Points

It sounds like there's something funny going on with the way the object lifecycle is implemented. A class shouldn't be disposing something that will be needed later, or perhaps the controller shouldn't be trying to use something beyond its lifespan. This might be a place where a "top down" analysis would be needed.