Kushal Seth
Kushal Seth

Reputation: 13

create global variables in asp.net C#

i have a web application with multiple pages. Each page is calling a class method to fetch data from database. Some of these calls are redundant, meaning we are firing queries multiple times to database to fetch same data. I want to query database once and store the result in some global variable, not sessions, so that pages can access those variables. I have already tried singleton pattern design, but it doesn't accept parameters while object creation. Please help

Upvotes: 0

Views: 1636

Answers (2)

Habib
Habib

Reputation: 223187

Use Application.Cache to store the result and then access it in multiple pages. But remember that this information will be shared by all the users of your site.

DataTable dataTable = GetDataFromDatabase();
HttpContext.Current.Cache["CahcedTable"] = dataTable;

To access it:

DataTable dataTable = HttpContext.Current.Cache["CachedTable"] as DataTable;
if(dataTable != null)
{
     //your code e.g. gridView1.DataSource = dataTable;
}

Upvotes: 3

Ronan Thibaudau
Ronan Thibaudau

Reputation: 3603

Use a static class, it (along with all it's static properties / fields) will only exist once per applucation domain (so, unless you do a few very specific thibgs, once per website)

Upvotes: 0

Related Questions