asp.netcachingglobal-asaxapplication-start

What's the best way to load highly re-used data in a .net web application


Let's say I have a list of categories for navigation on a web app. Rather than selecting from the database for every user, should I add a function call in the application_onStart of the global.asax to fetch that data into an array or collection that is re-used over and over. If my data does not change at all - (Edit - very often), would this be the best way?


Solution

  • You can store the list items in the Application object. You are right about the application_onStart(), simply call a method that will read your database and load the data to the Application object.

    In Global.asax

    public class Global : System.Web.HttpApplication
    {
        // The key to use in the rest of the web site to retrieve the list
        public const string ListItemKey = "MyListItemKey";
        // a class to hold your actual values. This can be use with databinding
        public class NameValuePair
        { 
            public string Name{get;set;} 
            public string Value{get;set;}
            public NameValuePair(string Name, string Value)
            {
                this.Name = Name;
                this.Value = Value;
            }
        }
    
        protected void Application_Start(object sender, EventArgs e)
        {
            InitializeApplicationVariables();
        }
    
    
        protected void InitializeApplicationVariables()
        {
            List<NameValuePair> listItems = new List<NameValuePair>();
            // replace the following code with your data access code and fill in the collection
            listItems.Add( new NameValuePair("Item1", "1"));
            listItems.Add( new NameValuePair("Item2", "2"));
            listItems.Add( new NameValuePair("Item3", "3"));
            // load it in the application object
            Application[ListItemKey] = listItems;
        }
     }
    

    Now you can access your list in the rest of the project. For example, in default.aspx to load the values in a DropDownList:

    <asp:DropDownList runat="server" ID="ddList" DataTextField="Name" DataValueField="Value"></asp:DropDownList>
    

    And in the code-behind file:

    protected override void OnPreInit(EventArgs e)
    {
        ddList.DataSource = Application[Global.ListItemKey];
        ddList.DataBind();
        base.OnPreInit(e);
    }