每个请求缓存实体框架DbContexts [英] Caching Entity Framework DbContexts per request

查看:93
本文介绍了每个请求缓存实体框架DbContexts的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个基于System.Entity.Data.DbContext的类。他们在Web应用程序的不同端点多次使用请求 - 实例化它们是否昂贵?



我在HttpContext.Current.Items中缓存了一个副本因为每个请求都没有权限拥有它们的几个副本,但是现在我已经发现,在请求结束时它不会被自动从HttpContext处理掉。在我编写代码来处理它之前(在Application_EndRequest中),我以为我会读取这些情况,因为如果我应该在需要它们的地方实例化它们并将它们处理在那里,那么真的没有点缓存它们。 p>

在互联网上已经问过类似的问题,但我似乎找不到一个能够正确回答我的问题的问题。



更新



我有发现处理上下文可能在这个博客帖子,但我仍然有兴趣听到他们是否昂贵的实例化在第一位。基本上,是否有很多EF魔术在幕后,我想避免经常太多?

解决方案

m回答我自己的问题的完整性。



答案提供了有关此问题的更多信息。



总而言之,实例化DbContext并不昂贵,所以不要担心。



此外,您也不需要担心处理数据上下文。您可能会注意到ScottGu不在他的示例中(他通常将上下文作为控制器上的私有字段)。 这个答案有一些很好的信息来自Linq to SQL团队关于处理数据上下文,以及这个博文也扩展了这个主题。


I have several classes based on System.Entity.Data.DbContext. They get used several times a request in disparate ends of the web application - is it expensive to instantiate them?

I was caching a copy of them in HttpContext.Current.Items because it didn't feel right to have several copies of them per request, but I have now found out that it doesn't get automatically disposed from the HttpContext at the end of the request. Before I set out writing the code to dispose it (in Application_EndRequest), I thought I'd readdress the situation as there really is no point caching them if I should just instantiate them where I need them and dispose them there and then.

Questions similar to this have been asked around the internet, but I can't seem to find one that answers my question exactly. Sorry if I'm repeating someone though.

Update

I've found out that disposing of the contexts probably doesn't matter in this blog post, but I'm still interested to hear whether they are expensive to instantiate in the first place. Basically, is there lots of EF magic going on there behind the scenes that I want to avoid doing too often?

解决方案

I'm answering my own question for completeness.

This answer provides more information about this issue.

In summary, it isn't that expensive to instantiate the DbContext, so don't worry.

Furthermore, you don't really need to worry about disposing the data contexts either. You might notice ScottGu doesn't in his samples (he usually has the context as a private field on the controller). This answer has some good information from the Linq to SQL team about disposing data contexts, and this blog post also expands on the subject.

这篇关于每个请求缓存实体框架DbContexts的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆