I have a huge XML document which I have to parse it to generate domain objects.
Because the document is huge, i don’t want to parse it every time a user requests it, but only first time, then saving all the objects into cache.
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;
}
How is the best way i can make this function working in singleton and be thread-safe?
Fixed the saving an object into cache method (was a copy-paste mistake)
Create a Lazy static and keep in memory for the lifetime of the application. And don’t forget the “true” part, that’s what makes it thread safe.
To add this to your model, just make it private and return _product.Value;
To create a singleton using Lazy<>, use this pattern.
Another lazy pattern for use within a context (i.e. Session)
Some Model that is saved in Session: