Reputation: 415
Would it be ok to have only one DataContext per app and share that through an singleton?
I ask this because i would like to have the DataContext in every form but i realized that, if i change some enity in one DataContext, i have ro refresh it, if used before.
eg form1:
db = GetContext()
item=(from p in db.Table where p.id=1 select p)
on another form
db = GetContext()
item=(from p in db.Table where p.id=1 select p)
item.value="test"
back on the original form i have to do
db.Refresh(RefreshMode.OverwriteCurrentValues, item)
even if i do a new
item=(from p in db.Table where p.id=1 select p)
(without the refresh) the value will not be updated
Is DataContext threadsafe?
Upvotes: 0
Views: 1956
Reputation: 75316
It is not okay when using DataContext
as singleton, DataContext
is implemented using Unit of Work pattern with internal cache inside, purpose of internal cache is to avoid the round trips to database and for changes tracking. Keeping DataContext
as singleton would make internal cache increasing then lead to memory-leak for the time being.
The best practice is the lifetime of DataContext should be per thread, most of IoC containers support this, just choose one and use.
DataContext
is not thread-safe, so presumably you implemented thead-safe singleton using static constructor or Lazy<>
Upvotes: 2
Reputation: 1503090
Would it be ok to have only one DataContext per app and share that through an singleton?
Well, that's certainly not what it's designed for - and if you had multiple threads performing multiple operations, it certainly wouldn't be a good idea.
Just like database connections, it's best to create the context when you need it, do whatever you need to do, then create a new one when you've got a new set of operations to perform.
Upvotes: 4