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

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

问题描述

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

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?

我是他们缓存的副本HttpContext.Current.Items,因为它并没有觉得不对劲让每个请求他们的多个副本,但现在我发现,它并不会自动从HttpContext的在处置的请求的结束。我开始写code处置它(在Application_EndRequest)之前,我想我会改变这种局势,因为实在是没有一点缓存他们,如果我应该只是他们的实例,我需要他们,处理他们那里,然后

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.

更新

我发现,上下文处置可能不会在<问题href=\"http://stephenwalther.com/blog/archive/2008/08/20/asp-net-mvc-tip-34-dispose-of-your-datacontext-or-don-t.aspx\"相对=nofollow>这个的博客文章,但我仍然有兴趣听听他们是否在首位实例昂贵。基本上,有很多神奇的EF对那里发生的幕后,我想避免这样做太频繁?

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.

<一个href=\"http://stackoverflow.com/questions/813457/instantiating-a-context-in-linq-to-entities/813689#813689\">This答案提供了有关此问题的详细信息。

This answer provides more information about this issue.

总之,这是不贵实例化的DbContext,所以不用担心。

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

此外,你真的不需要担心任何处理数据的上下文。您可能会注意到ScottGu他的样品中不会(他通常情况下为控制器上的私有字段)。 <一href=\"http://stackoverflow.com/questions/389822/when-should-i-dispose-of-a-data-context/389871#389871\">This答案已经从LINQ到SQL团队处理有关数据上下文一些好的信息和<一个href=\"http://stephenwalther.com/blog/archive/2008/08/20/asp-net-mvc-tip-34-dispose-of-your-datacontext-or-don-t.aspx\"相对=nofollow>这个的博客文章也扩展了这个问题。

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天全站免登陆