EF中的DbContext是否应具有较短的使用寿命? [英] Should the DbContext in EF have a short life span?

查看:64
本文介绍了EF中的DbContext是否应具有较短的使用寿命?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务器上有一些长期运行的任务。基本上,它们就像是计划任务,它们会不时运行。

I have a few long running tasks on my server. Basically they are like scheduled tasks - they run from time to time.

它们都需要访问数据库,为此,我使用实体框架。每个任务都使用DbContext进行访问。

They all required access to the DB and I use Entity Framework for that. Each task uses a DbContext for access.

应该在每次运行时重新创建DbContext对象还是应该重用它?

Should the DbContext object be recreated on every run or should I reuse it?

推荐答案

我应该说取决于,因为在某些情况下,两个答案都有效,但是最合理的答案是应在不需要上下文时立即处置上下文

I should say "it depends" as there are probably scenarios where both answers are valid, however the most reasonable answer is "the context should be disposed as soon as it is not needed" which in practice means "dispose rather sooner than later".

这种答案带来的风险是,新来者有时会得出结论,应尽可能地处理上下文有时这会导致我检查代码,其中有连续的使用创建上下文,将其用于一个或两个操作,进行处理,然后在下一行出现另一个上下文。当然也不建议这样做。

The risk that comes from such answer is that newcomers sometimes conclude that the context should be disposed as otfen as possible which sometimes lead to a code I review where there are consecutive "usings" that create a context, use it for one or two operations, dispose and then another context comes up next line. This is of course not recommended also.

对于Web应用程序,自然生命周期与Web请求的生命周期相关。对于系统服务/其他长期运行的应用程序,生命周期策略之一是每个业务流程实例 /每个用例实例,其中业务处理/用例实现定义了自然的边界,而上下文的单独实例才有意义。

In case of web apps, the natural lifecycle is connected with a lifecycle of web requests. In case of system services / other long running applications one of lifecycle strategies is "per business process instance" / "per usecase instance" where business processing / use case implementations define natural borders where separate instances of contexts make sense.

这篇关于EF中的DbContext是否应具有较短的使用寿命?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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