🤯 50% Off! 700+ courses, assessments, and books

Setting Global Objects in Global.asax

Philip Miseldine
Share

From a forum request :)

ASP.NET includes a Global.asax file which exposes many application-wide events which you can use to control your application execution.

It also allows you to define globally-scoped objects. However, a word of caution…as each page in an ASP.NET page runs in its own thread, you need to make sure your objects are thread safe for multiple users requesting your site.

Why is this important? Imagine 2 requests, from user A and user B. Each request runs in a separate thread, and user A manipulates a global object in one thread, and user B manipulates the same object in a different thread. Depending on Windows, these might be executed in any order…meaning your global object won’t be synchronized for both users.

So to avoid this complication, use thread-safe objects, or, of particular interest, use a hashtable as a thread-safe container for your variables:


using System;
using System.Collections;

namespace MyApp.Collections {

public class globalVariableStore{
private Hashtable myCollection;
private Hashtable threadSafeCollection;

public globalVariableStore()
{
myCollection = new Hashtable();
threadSafeCollection = Hashtable.Synchronized(myCollection);
}

public void addVariable(string name, object value)
{
threadSafeCollection[name] = value;
}

public object retrieveVariable(string name) {
return threadSafeCollection[name];
}
}
}

You can then define an instance of your globalVariableStore as globally-scoped by adding a line to your global.asax file:


You can now access the object through “myVariables” from anywhere in your application.

Alternatively, you can use the Application object to store variables, such as:


Application["myvariable"] = "foo";

Yet, creating your own global objects can give far greater depth and control over globally defined object instances…just make sure they are thread safe!

Persistent Storage

Yet another mechanism is to add string values to your web.config file, which are then always available to your application:




This should be placed under the “configuration” element in the file.

You can then retrieve the value thus:


string connectionString = ConfigurationSettings.AppSettings("connectionString");

Remember, web.config files can’t be served over your server to a browser, so this affords some security, but valuable information is stored in plain-text on your server, so it might be an idea to encrypt some sensitive strings beforehand!