在Global.asax中的DbContext的静态字段与在控制器类的DbContext的实例字段? [英] Static field of DbContext in Global.asax versus instance field of DbContext in controller class?

查看:122
本文介绍了在Global.asax中的DbContext的静态字段与在控制器类的DbContext的实例字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

坦白地说,我在C#和Asp.net MVC一个新手。
我也不知道asp.net web应用程序实际上是如何运转的幕后IIS和AS​​P.NET框架。

Frankly I am a newbie in both C# and Asp.net MVC. I also do not know how the asp.net web application actually works on IIS and ASP.NET framework behind the scene.

我很困惑与在那里我有我的asp.net MVC应用程序申报的DbContext的领域(或从的DbContext派生的任何类)的决定。

I am confused with the decision where I have to declare a field of DbContext (or any class derived from DbContext) in my asp.net mvc application.

我有两个选择:


  1. 声明的Global.asax 使得所有控制器都可以利用它。
  2. 里面的字段作为静态字段
  3. 声明字段作为每个控制器类内部的实例字段。

  1. Declare the field as a static field inside global.asax such that all controllers can make use of it.
  2. Declare the field as an instance field inside each controller class.

您能解释一下哪个是正确的?更详细的解释是真正需要的。

Could you explain which one is the correct one? More detailed explanation is really needed.

推荐答案

如果你把它在Global.asax中静态字段,你会遇到并发问题。来自多个请求多个线程可以进来,并得到对方的数据。我已经看到它在我自己的网站,它不是pretty。

If you make it a static field in global.asax, you will run into concurrency problems. Multiple threads from multiple requests can come in and get each other's data. I've seen it on my own sites, and it isn't pretty.

为实体框架和LINQ to SQL上下文类被设计为一个轻量级的实例,您为每一组要运行查询的东西。这并不意味着要长期生活。

The context classes for both Entity Framework and LINQ to SQL were designed to be a lightweight instantiation, something you set up for each set of queries you want to run. It's not meant to be long lived.

查看关于同一主题的这另一个堆栈溢出问题/答案,措辞不同。

这篇关于在Global.asax中的DbContext的静态字段与在控制器类的DbContext的实例字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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