Using HttpContext.Current.Application to store simple data

后端 未结 5 1061
旧时难觅i
旧时难觅i 2020-12-09 19:02

I want to store a small list of a simple object (containing three strings) in my ASP.NET MVC application. The list is loaded from the database and it is updated rarely by ed

5条回答
  •  一个人的身影
    2020-12-09 19:32

    What you actually do is Caching, and it's great, since you reduce calls to an external storage (a database or a file, whatever). The trade-off is memory usage, of course. Now, almost any modern web framework, including ASP.NET, includes some kind of a caching mechanism. Either you use it, or you use some kind of a global variable.

    Storing data in ASP.NET's built-in Cache object has some significant advantages, since this mechanism actually checks the memory usage and removes the cached data according to some rules.

    However, if the data you want to cache is intensively used across the application, and its size is not too large (say, smaller than 1 MB), you may want to store it in as a global variable.

    In ASP.NET, global variables are achieved by either using the Application object, like you described in your question, or by writing public static properties/fields in an internal/public class.

    Here's my solution to static properties. Note that I use a locking object, to protect the inner data from corruption. It looks like this:

    public class WhateverClass
    {
      private static object theLocker = new object();
      private static YourDataType theData;
      public static YourDataType TheData
      {
        get
        {
          lock (theLocker)
          {
            return theData;
          }
        }
        set
        {
          lock (theLocker)
          {
            theData = value;
          }
        }
      }
    }
    

    The usage is very simple:

    First time, in Application_Start:

    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
    
        WhateverClass.TheData = loadDataFromSql();
    }
    

    In any controller:

    var myData = WhateverClass.TheData;
    

    This approach is better because you have type safety, since this public static property can be explicitly declared with the exact type. In addition, this kind of storage is more testable since it doesn't depend on the web context.

    HTH!

提交回复
热议问题