grautur
grautur

Reputation: 30475

problems with data contexts and disposing

I have some C# code that looks like

using (DataContext db = new DataContext(Program.config.dbContextStr)) {
    Foo.bar(db);
}

So bar is a static method of class Foo, and bar uses the db object passed in. It also passes db object to some other methods that it calls.

The problem is that I'm getting this exception:

System.ObjectDisposedException: Cannot access a disposed object. 
Object name: 'DataContext accessed after Dispose.'.

I've looked around for solutions and people have suggested to forget the using declaration and to simply write:

DataContext db = new DataContext(blah);
Foo.bar(db); 
// Let the garbage collector go about its merry business.

and to disable deferred loading:

db.DeferredLoadingEnabled = false;
Foo.bar(db);

I've tried both of these solutions, but I still get the exception. Are there other things I should try?

Upvotes: 0

Views: 119

Answers (2)

Pieter van Ginkel
Pieter van Ginkel

Reputation: 29632

You are disposing the data context.

Firstly, the way you are using the data context is correct, wrapping it in a using.

This means that somewhere inside Foo.bar, you are disposing your data context; there is no other alternative.

This means you have to search your code for either one of the following constructs:

  • db.Dispose(); or

  • using (db) { ... }.

Try to do a "Find all" in Visual Studio on the word "Dispose" or "using" and manually check all instances.

Upvotes: 1

Aliostad
Aliostad

Reputation: 81660

I suspect that you are disposing the DataContext in the Foo.bar(db);

Upvotes: 0

Related Questions