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

Shantanu Gupta picture Shantanu Gupta · Nov 25, 2009 · Viewed 49.9k times · Source

I have some data layer classes that are to be used very frequently almost on the whole site.

I was working on a windows application previously and i used to create its object in module (vb.net) but now i m working in C# and on ASP.NET.

Now i need to do same thing so that i need not create same object multiple times on every page.
I want to use something like using a global variable.

How can i do this?
Is it done by using global.asax
can i create my objects in global.asax

I am a new to asp.net, so try to give the syntax along with an explanation.

Answer

Bob picture Bob · Nov 25, 2009

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.