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?
It is not okay when using
DataContextas singleton,DataContextis 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. KeepingDataContextas 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.
DataContextis not thread-safe, so presumably you implemented thead-safe singleton using static constructor orLazy<>