如何访问Global.asax静态成员?
如果我们在 Global.asax 中声明一个 static 变量,那么如何在 ASP.NET 页面中访问它?
<script runat=server">
public static object myObject = new MyClass();
// Application_Start() and other stuff goes here.
</script>
而且,这对于存储全局对象(所有请求的同一实例)是一个好主意吗?
If we declare a static
variable in Global.asax
then how to access it inside an ASP.NET
page ?
<script runat=server">
public static object myObject = new MyClass();
// Application_Start() and other stuff goes here.
</script>
And, is this a good idea for storing a global object (same instance for all requests) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
myObject 应该可用于 global.asax 中和 ASP.NET 页面内的所有方法
myObject should be available to all the methods in global.asax and inside your ASP.NET pages using
将对象创建为单例可能比将其作为“全局”对象更好。在应用程序启动时实例化它,并在应用程序结束时销毁它。只要您不需要它跨网络农场,您就非常安全。
请参阅这篇文章及其评论。
It may be better to create your object as a singleton rather than putting it as a "global" object. Instantiate it in application start, and destroy it in application end. As long as you don't need it to be across web farms, you're pretty safe.
See this post and its comments.
http://weblogs.asp.net/jeff/archive/2007/09/21/how-do-you-get-a-true-singleton-in-an-asp-net-app.aspx
就我个人而言,我强烈反对在 ASP.NET 中使用全局变量。几年前我有过相当糟糕的经历。
您应该同步对全局
MyClass
实例的成员的访问,以确保它在多线程场景中正常工作(如果出现多个请求,则可能/强制)。您还可以使用
ApplicationState
,根据 Microsoft 的说法,您不应该。Personally, I would strongly vote against using global variables in ASP.NET. I had rather bad experiences some years back.
You should synchronize access to the members of your global
MyClass
instance to ensure it works correctly in a multi-threading scenario (which is likely/mandatory if multiple requests come in).There is also the
ApplicationState
which you could use, according to Microsoft, you shouldn't.全局未定义
这对我有用:
ASP.global_asax
示例
ASP.global_asax.DefaultModel.GetTable("Tags");
Global is not defined
that works for me:
ASP.global_asax
example
ASP.global_asax.DefaultModel.GetTable("Tags");