DataContext lifespan

Aug 16, 2008 at 9:39 PM
Vijay and I were having this discussion on email, moving it here:

> <<< re: MS team's recommendation on DataContexts >>>
>> Good point. I'm still not sure the right thing to do with db data
>> contexts. If you have an official MS guy statement saying that should
>> be done. Without much effort, we could hide recycle/refresh the data
>> context instance inside the DatabaseIndexSet<T>, rather than making
>> the DataContext settable. What do you think we should do?
>
> The recommendation I'm talking about was in the MS Press book
> Programming Microsoft LINQ; it may be online as well, I haven't looked
> for it.  I would think that having the DatabaseIndexSet recycle its
> DataContext is a fine idea; I was thinking about it after I wrote the
> question, though, and I can't help but wonder if it wouldn't be a
> tradeoff between the object tracking overhead that the MS guys were
> warning against and the overhead of reflection to create new
> datacontexts by type.  Unless you were thinking of a different way to
> recycle the DataContext that I'm not thinking of...

Hmmm, I still have no idea what to do with DataContext instances - how
long they should live and when i should kill them.
The "Unit of work" rule idea seems to be a good one, except not sure
how large units of work can be.
I'm eager to leave the DataContext instance as a singleton (i.e. one
always open instance) and wait until you come across an error during
periodic updates - just as an experiment to see what goes wrong.

I also found this online discussion of why it's best to keep the DataContext as a UoW, and it seems that the main reason has to do w/ avoiding concurrency conflicts:

http://blogs.msdn.com/dinesh.kulkarni/archive/2008/04/27/lifetime-of-a-linq-to-sql-datacontext.aspx

I wonder if it wouldn't be better to offer a choice.  If you used an untyped datacontext internally, I think you could take the connection (or connectionstring) of the database and then create and destroy the datacontext on each use, I would think. The developer wouldn't even have to cast on a query, since you coudl still use GetTable<T> under the hood. 

Thoughts?