How to access Global.asax static members?
If we declare 开发者_JAVA百科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) ?
myObject should be available to all the methods in global.asax and inside your ASP.NET pages using
Global.myObject
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
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.
Global is not defined that works for me:
ASP.global_asax example
ASP.global_asax.DefaultModel.GetTable("Tags");
精彩评论