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)