C# Linq-to-Sql - Should DataContext be disposed using IDisposable
Asked Answered
T

1

29

I have several methods that deal with DB and all of them start by calling

FaierDbDataContext db = new FaierDbDataContext();

Since the Linq2Sql DataContext object implements IDisposable, should this be used with "using"?

using (FaierDbDataContext db = new FaierDbDataContext()) {
    // use db here
}

What are the implications of using it one way or another?

Topsail answered 4/5, 2009 at 19:27 Comment(1)
Also, a side note, for people using LINQ you shouldn't keep an instance variable of your datacontext for your data model class. Instead, declare one every time you need to in your methods.Shinn
D
30

Unlike most types which implement IDisposable, DataContext doesn't really need disposing - at least not in most cases. I asked Matt Warren about this design decision, and here was his response:

There are a few reasons we implemented IDisposable:

  • If application logic needs to hold onto an entity beyond when the DataContext is expected to be used or valid you can enforce that contract by calling Dispose. Deferred loaders in that entity will still be referencing the DataContext and will try to use it if any code attempts to navigate the deferred properties. These attempts will fail. Dispose also forces the DataContext to dump its cache of materialized entities so that a single cached entity will not accidentally keep alive all entities materialized through that DataContext, which would otherwise cause what appears to be a memory leak.
  • The logic that automatically closes the DataContext connection can be tricked into leaving the connection open. The DataContext relies on the application code enumerating all results of a query since getting to the end of a resultset triggers the connection to close. If the application uses IEnumerable's MoveNext method instead of a foreach statement in C# or VB, you can exit the enumeration prematurely. If your application experiences problems with connections not closing and you suspect the automatic closing behavior is not working you can use the Dispose pattern as a work around.

from the source

Dumbhead answered 4/5, 2009 at 19:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.