Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

c# - Multiple/single instance of Linq to SQL DataContext

I have a project with a number of different classes querying and modifying data in a common set of tables. I've set up a .dbml file which provides us with a DataContext class. My question is whether a single instance of the DataContext should be used by all objects, or whether multiple instances are safe to use. I'm also wondering about thread safety in the case of a single DataContext, and whether access to it's methods should be synchronized.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Rick Strahl has a nice article about your options: http://www.west-wind.com/weblog/posts/246222.aspx.

See also: LINQ to SQL - where does your DataContext live?.

You may want a slightly different strategy for each type of deployment - web, desktop, windows service...

Summarized, your options are:

  • Global DataContext - dangerous in multi-threaded environments (including web apps). Remember that instance members are not guaranteed to be thread-safe (from Bradley Grainger's answer above).
  • DataContext per thread - complicated. If your DataContext is tracking changes you must be sure to flush them at the appropriate time. Instantiating, storing, and retrieving the DataContext is a pain.
  • DataContext per atomic action - you lose the ability to track changes since one DataContext creates an object while another updates or deletes it. Attaching a data object to a new DataContext may not work like you expect.
  • DataContext per data object - seems inelegant because you have to fuss with the DataContext on instantiation(create and attach) and update/delete (pull it off the data object and use it).

I opted for a DataContext per data object. It may not be the fanciest solution but it works in all deployment environments.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...