Create Lazy static and save memory for the entire life of the application. And do not forget about the "true" part, which makes it thread safe.
public static readonly Lazy<List<Product>> _product = new Lazy<List<Products>>(() => GetProducts(), true);
To add this to your model, just make it private and return _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; } } }
To create a singleton using Lazy <>, use this template.
public MyClass { private static readonly Lazy<MyClass> _myClass = new Lazy<MyClass>(() => new MyClass(), true); private MyClass(){} public static MyClass Instance { get { return _myClass.Value; } } }
Update / Edit:
Another lazy pattern to use in context (i.e. session)
Some model that is saved in the session:
public MyModel { private List<Product> _currentProducts = null; public List<Product> CurrentProducts { get { return this._currentProducts ?? (_currentProducts = ProductDataLayer.GetProducts(this.CurrentCustomer)); } } }
source share