Linq and DataContext

大城市里の小女人 提交于 2019-12-04 19:06:19

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<>

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!