posted by 네코냥이 2013. 6. 26. 14:26


Although DataContext/ObjectContext implement IDisposable, you can (in general)

get away without disposing instances. Disposing forces the context’s connection

to dispose—but this is usually unnecessary because L2S and EF close connections

automatically whenever you finish retrieving results from a query.

Disposing a context can actually be problematic because of lazy evaluation. Con-

sider the following:

IQueryable<Customer> GetCustomers (string prefix)

{

  using (var dc = new NutshellContext ("connection string"))

    return dc.GetTable<Customer>()

             .Where (c => c.Name.StartsWith (prefix));

}

...

foreach (Customer c in GetCustomers ("a"))

  Console.WriteLine (c.Name);

This will fail because the query is evaluated when we enumerate it—which is

after disposing its DataContext.

There are some caveats, though, on not disposing contexts:


• It relies on the connection object releasing all unmanaged resources on the

Close method. While this holds true with SqlConnection, it’s theoretically

possible for a third-party connection to keep resources open if you call

Close but not Dispose (though this would arguably violate the contract de-

fined by IDbConnection.Close).


• If you manually call GetEnumerator on a query (instead of using foreach) and

then fail to either dispose the enumerator or consume the sequence, the con-

nection will remain open. Disposing the DataContext/ObjectContext provides

a backup in such scenarios.


• Some people feel that it’s tidier to dispose contexts (and all objects that im-

plement IDisposable).

If you want to explicitly dispose contexts, you must pass a DataContext/Object

Context instance into methods such as  GetCustomers to avoid the problem

described.