ASP.net缓存+单例模式

Cat*_*lin 5 asp.net singleton caching

我有一个巨大的XML文档,我必须解析它以生成域对象.

因为文档很大,我不想在每次用户请求时解析它,而只是第一次,然后将所有对象保存到缓存中.

public List<Product> GetXMLProducts()
{
    if (HttpRuntime.Cache.Get("ProductsXML") != null)
    {
        return (List<Product>)(HttpRuntime.Cache.Get("ProductsXML"));
    }

    string xmlPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content\\Products.xml");
    XmlReader reader = XmlReader.Create(xmlPath);
    XDocument doc = XDocument.Load(reader);

    List<Product> productsList = new List<Product>();
    // Parsing the products element

    HttpRuntime.Cache.Insert("ProductsXML", productsList);
    return productsList;
}
Run Code Online (Sandbox Code Playgroud)

如何使这个函数在单例中工作并且是线程安全的最好方法是什么?

修复了将对象保存到缓存方法(是一个复制粘贴错误)

Chr*_*ler 10

创建一个Lazy静态并在内存中保留应用程序的生命周期.并且不要忘记"真正的"部分,这就是它使线程安全的原因.

public static readonly Lazy<List<Product>> _product = new Lazy<List<Products>>(() => GetProducts(), true);
Run Code Online (Sandbox Code Playgroud)

要将其添加到模型中,只需将其设为私有并返回_product.Value;

public MyModel
{
    ... bunch of methods/properties

    private static readonly Lazy<List<Product>> _products = new Lazy<List<Products>>(() => GetProducts(), true);

    private static List<Product> GetProducts()
    {
        return DsLayer.GetProducts();

    }

    public List<Product> Products { get { return _products.Value; } }
}
Run Code Online (Sandbox Code Playgroud)

要使用Lazy <>创建单例,请使用此模式.

public MyClass
{
    private static readonly Lazy<MyClass> _myClass = new Lazy<MyClass>(() => new MyClass(), true);

    private MyClass(){}

    public static MyClass Instance { get { return _myClass.Value; } }
}
Run Code Online (Sandbox Code Playgroud)

更新/编辑:

在上下文中使用的另一种懒惰模式(即Session)

在Session中保存的一些模型:

public MyModel
{
   private List<Product> _currentProducts = null;
   public List<Product> CurrentProducts 
   {
      get
      {
         return this._currentProducts ?? (_currentProducts = ProductDataLayer.GetProducts(this.CurrentCustomer));
      }
   }
}
Run Code Online (Sandbox Code Playgroud)