We're using Linq to SQL here. At present, our repositories tend to new up their own DataContext objects, so if you're working with several repositories, you're working with several DataContexts.
I'm doing some refactoring to allow dependency injection in our work. I have assumed that we would want a '1 DataContext per request' pattern, so I'm injecting the same DataContext (unique to the web request) into all the repositories.
But then something happened today. Following my refactoring, we got a ForeignKeyReferenceAlreadyHasValueException because a foreign key field was set instead of the corresponding association property being set. So far as I can tell from Google, setting the foreign key directly is wrong in Linq to SQL (i.e. our code was wrong to do this), but we never got the error until after I had done the refactoring.
So I just wanted to check - is one DataContext per request definitely the right way to go?
One DataContext per request is one way to go, not the only one, but usually a good one.
By using a single DataContext you can save all submits to the end of the request and submit all changes at once. SubmitChanges automatically encapsulates all changes in a transaction.
If you use multiple contexts you need to encapsulate your request in a transaction instead to make it possible to rollback changes if the request fails halfway through. You get a little more overhead using multiple contexts but that is usually not significant.
I have worked with both single and multiple datacontexts in different applications and both works good, if it requires to much rewrite to go to a single DataContext you can keep multiple contexts if you don't have any other strong reason for a rewrite.