views:

788

answers:

3

I have some data layer classes that r to be used very frequently, Almost in whole site. I was working on window 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 as 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 newbie in asp.net, so try to be syntatical along with xplanation.

Thx in advance

+2  A: 

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.

Bob
but it says to make all functions to be static for that which i cant, so how would i use that...
Shantanu Gupta
Just have the class only contain your variables so they are all contained in one place. Put your methods somewhere else,
Bob
static state is a bad idea in ASP.NET. Use Application and Cache instead.
Henk Holterman
@Henk Holterman - Why is it a "bad idea"? Do you realize that Application and Cache both are static instances. statics might not be thread safe depending on your instance type, but that is another question.
Bob
+2  A: 

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

XpiritO
what is the use of application state with my context.I have no idea of applicaton state
Shantanu Gupta
A: 

"ASP.NET Application State Overview" contains an object that can be used to store data across all users, similar to the Session object in terms of being able to store various key-value pairs.

JB King