Should data contexts be static?

风流意气都作罢 提交于 2019-11-27 06:51:45

问题


I am using entity framework 4 and I create an datacontext for model in one of the base classes. But I was in profiling it and the context is being created every time I try to query, So I thought of making it static so that it is created only once and reused always.

Do you think this is the best way to do it and data/object context should always be made static? Are there any disadvantages to making it static? Should data contexts be static or non-static? Any ideas or suggestions are welcome.


回答1:


No. They should not always be static.

You can actually run in to many more issues with a Static Data Context rather than the non-static equivalent (like multiple users from separate sessions accessing the same context from multiple threads).

I'm not going to go into the detailed explanation since there are some very good blog posts out there covering the details:

Linq to SQL DataContext Lifetime Management - Rick Strahl's Web Log (may not seem relevant, but still is)

Making Entity Framework (v1) work, Part 1: DataContext Lifetime Management (for a possible alternative if you don't like Rick's solution)




回答2:


Should data contexts be always static?

No, they should (almost*) never be static. DataContext are cheap to create because they are meant to be used as a unit of work. Thus you should have one DataContext per "conversation" (whatever that happens to mean for your context).

*: The correct answer is probably that they should never be static, but I'm always skeptical of programming advice that is always or never. Thus, this is a weenie wiggle more than anything.



来源:https://stackoverflow.com/questions/4081071/should-data-contexts-be-static

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