Using HttpContext.Current.Application to store simple data

后端 未结 5 1065
旧时难觅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:09

    HttpContext.Current.Application is essentially a hangover that is needed for backwards compatibility with classic ASP. It's essentially a static Hashtable with classic ASP locking semantics (Application.Lock / Application.UnLock).

    As a weakly-typed Hashtable, you will need to cast objects you retrieve:

    MyObject myObject = (MyObject) HttpContext.Current.Application["myObject"];
    

    In an ASP.NET application that is not a migration from classic ASP, I would prefer using other standard .NET stuff, such as:

    • A static field, using .NET locking semantics if you need locking (e.g. the C# lock keyword, or a ReaderWriterLockSlim instance, depending on your requirements):

      static MyObject myObject = LoadFromSql();

    • The ASP.NET Cache - which has rich functionality for managing expiration, dependencies, ...

提交回复
热议问题