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

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

问题描述

坦白说,我是C#和Asp.net MVC中的新手。
我也不知道asp.net Web应用程序如何实际在IIS和ASP.NET框架之后工作。



我对决定感到困惑我必须在我的asp.net mvc应用程序中声明一个DbContext(或任何派生自DbContext的类)的字段。



我有两个选择:


  1. 将该字段声明为 global.asax 中的静态字段,以便所有控制器都可以使用它

  2. 在每个控制器类中声明该字段为实例字段。

哪一个是正确的?

解决方案

如果您在global.asax中将其设为静态字段,则会遇到并发问题。来自多个请求的多个线程可以进入并获取彼此的数据。更糟糕的是,直到您开始在您的网站上获得更多流量,或者直到您开始加载测试,这才会显示。你会实现它作为一个单身,所有的将在你的测试工作,你会认为,我是一个天才!看看这个实现是多么干净!但是有一天,像我一样,你会被烧毁。结果会混淆,用户将开始看到不属于他们的数据,网站会出现意外。



实体框架和LINQ的上下文类到SQL被设计为一个轻量级的实例化,你为每一组你想要运行的查询设置的东西。这并不意味着要长久居住。



查看这个其他Stack Overflow问题/答案在同一主题,措辞不同。


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.

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.

I have two choices:

  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.

解决方案

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. What's worse is that this will not show up until you start getting more traffic on your website, or until you start load testing. You'll implement it as a singleton, all will be working well in your testing, and you'll think, "I'm a genius! Look how clean this implementation is!" But someday, you will be burned by this, as I have been. Results will get mixed up, users will start seeing data that doesn't belong to them, and the website will behave unexpectedly.

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.

Check out this other Stack Overflow question / answer on the same topic, worded differently.

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

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