Global Objects

J

JustinCarmony

Hi,

I'm a PHP programmer who has been hired by a company to do web
applications, but they want me to use ASP .NET. For the most part, the
transition has been relatively smooth. However, I have a question:

In PHP, I would create a class that I called DBContol that would be the
intermediary for all communications between my web application and
Database. I would execute a command something like this:

<?
// This
$GLOBALS["mainDB"] = new DBControl("DatabaseName");

// or I would store it in the session
$_SESSION["mainDB"] = new DBControl("DatabaseName);

// Then I would be able to execute commands something like this:

$_SESSION["mainDB"]->query($queryString);
?>

Now, in ASP .NET I know there is a Global.asax file that you create
that is the "root" of the application and is the very first executed,
depending on what EventHandler you use. You also use an <object> tag to
declare objects used across the application.

The problem is, I can't really get this to work. So here is my
question:

How can I create an instance of a class in my application that can
access that object where ever needed in the code, how do I access it
and run it's methods, and make sure that its a sound and secure way of
doing this. I've looked for tutorials, and they all talk about storing
variables globally, but I need to access this instance of a class no
matter where in the code.

Any suggestions? Thanks in advance for any replies.
 
J

JustinCarmony

Also, some of the errors I experiences while trying this.

I would set the <object> tag in the Global.asax, and later in the
program I tried to do this in the Global.asax's Application_Start():

void Application_Start(object sender, EventArgs e)
{
mainDB = new DBControl("mainDB");
}

and it told me that mainDB was read only.

I'm still going to play with it and keep checking back and posting
progress.
 
A

Aidy

To answer your question, in Application_Start you would;

Application["myDB"] = new DBControl("mainDB");

Then when you need to use it on a page;

DBControl mainDB = (DBControl) Application["myDB"];
mainDB.SomeMethod();

However you are better making sure the methods on your DBControl class are
all static and don't persists any data in the class itself across method
calls. That way you can simply use this code;

DBControl.SomeMethod();

anywhere in your code without the need to store anything globally.

You can combine the two techniques using the "singleton pattern" (google
it).

However do look to using static methods on your class and get away ftom the
whole "global variable" methodology.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top