为什么没有一个人的WebAPI控制器手术后处置的DbContext? [英] Why does no one disposes DbContext after WebApi controller operation?
问题描述
我所知道的各种教程,以及完整的例子定位的WebAPI
&放大器; 实体框架
(甚至从微软)有的WebAPI
控制器是这样的:
I am aware of various tutorials as well as complete examples targeting WebApi
& Entity Framework
(even from Microsoft) that have WebApi
controller like this:
public HttpResponseMessage GetInternet(int id) {
var context = new InternetDbContext();
var result =
(from internet in context.Internets
where internet.Id.Equals(id)
select internet).FirstOrDefault();
if(result != null)
Request.CreateResponse(HttpStatusCode.OK, result);
}
但是,当我得知实体框架
如2年前,我发现对框架的每个资源指出,这是为处理废弃在 DbContex
在的最短的可能寿命,例如:与使用
。而如今,人们似乎不给狗屎处理任何事情(他们的经理,仓库,DI容器......)。
But when I learnt about Entity Framework
like 2 years ago, every resource I found about the framework pointed out how extremely important it is to DISPOSE the DbContex
in the SHORTEST possible lifespan, e.g. with 'using
'. And nowadays, people seem to don't give a shit about disposing anything (their managers, repositories, DI containers...).
我失去了一些东西呢?请问API调用结束时自动部署的背景下?还是我必须使用像的Htt prequestMessageExtensions.RegisterForDispose()
的<一个href="http://msdn.microsoft.com/en-us/library/dn153859(v=vs.118).aspx">http://msdn.microsoft.com/en-us/library/dn153859(v=vs.118).aspx?
Am I missing something here? Does the end of the API call automatically disposes the context? Or do I have to use something like HttpRequestMessageExtensions.RegisterForDispose()
from http://msdn.microsoft.com/en-us/library/dn153859(v=vs.118).aspx?
推荐答案
就个人而言,每当我看到的类型实现的IDisposable
,我几乎可以肯定,我要去使用使用
语句这种类型的新实例工作时。
Personally, whenever I see the type implements IDisposable
, I'm almost certain that I'm going to use a using
statement when working with new instances of this type.
在该变量超出范围(如在你的情况与上下文
变量超出作用域时,从 GetInternet 执行返回code>法),它的内存最终会被垃圾收集器回收,但是,这并不意味着任何原生处理(如文件处理程序或数据库连接)将要关闭,这就可以有一个非常严重的负面影响您的应用程序。
When the variable goes out of scope (like in your case with the context
variable going out of scope when the execution returns from GetInternet
method), its memory is eventually going to be reclaimed by garbage collector but this doesn't mean that any native handlers (e.g. file handlers or database connections) are going to be closed which can have a very serious negative impact on your application.
因此,考虑的总是的包装的的IDisposable
到使用
结构:
So, consider always wrapping an IDisposable
into the using
construct:
using (var context = new InternetDbContext())
{
// Your code goes here
}
希望这有助于。
Hope this helps.
这篇关于为什么没有一个人的WebAPI控制器手术后处置的DbContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!