Cornwell
Cornwell

Reputation: 3410

Correct way of using variables from global.asax

I have a simple global.asax file that runs some code at startup and stores a handle in a variable. I want to access that variable from my other files in the project. Here is my global.asax:

<%@ Application Language="C#" %>
<script runat="server">

    static JustTesting justTesting;
    static public JustTesting JustTesting { get { return justTesting ; } }

    void Application_Start(object sender, EventArgs e) 
    {
        //my code here
    }

    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown

    }

    void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs

    }
</script>

And when I want to use that variable...

ASP.global_asax.JustTesting

...which works, but I'm sure there must be a more elegant way of calling it instead of having to add ASP.global_asax. all the time.

Upvotes: 0

Views: 1918

Answers (1)

Robert
Robert

Reputation: 3302

You can use Application object.

Reading:

var x = Application["x"];

Writing:

Application.Lock();
Application["x"] = "value";
Application.UnLock();

Reference: http://msdn.microsoft.com/en-us/library/94xkskdf(v=vs.90).aspx

You can also create your own class, which should be thread safe.

Upvotes: 1

Related Questions