How to create Global variables, ASP.NET, global asax

You don't actually need to use the global.asax. You can make a class that exposes your objects as statics. This is probably the most simple way

public static class GlobalVariables {
    public static int GlobalCounter { get; set; }
}

You can also use the Application State or even the ASP.NET Cache because those are shared across all sessions.

However, If I were in this situation, I would use a framework like Spring.NET to manage all my Sington instances.

Here is a quick example of how you would get at your class instances using Spring.NET

//The context object holds references to all of your objects
//You can wrap this up in a helper method 
IApplicationContext ctx = ContextRegistry.GetContext();

//Get a global object from the context. The context knows about "MyGlobal"
//through a configuration file
var global = (MyClass)ctx.GetObject("MyGloblal");

//in a different page you can access the instance the same way
//as long as you have specified Singleton in your configuration

But really, the bigger question here is why do you need to use global variables? I am guessing you don't really need them and there might be a better big picture soluion for you.


I would recomend you to use application state for this purpose.