The below code throws an error of "Object reference not set to an instance of an object" When calling mycache.Get(“products”). Im using a WCF application. Im not 100% im using caching correctly. Any advice?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Caching;
namespace DataLayer {
public class Products
{
public List<Product> Current()
{
Cache mycache = new Cache();
if (mycache.Get("products")== null)
{
using (DataLayer.AccessDataContext db = new AccessDataContext())
{
var products = from p in db.fldt_product_to_supp_parts
where p.Current
select new Product
{
WholesaleCode = p.WholesaleCode,
ProductCode = p.Product_Code
};
mycache["products"] = products.ToList();
}
}
return mycache["products"] as List<Product>;
}
} }
EDIT : I’m using .net 3.5
From the look of the documentation you shouldn’t be creating your own instance of the
Cacheclass (it says the constructor is for framework use only). Try usingCache.Getinstead?EDIT (in response to comment)…
From the MSDN docs here:
So, it looks like
Cache.Getis available when you’re within a Page; otherwise you can callHttpContext.Cacheto get the active cache. Either way, there’s a singleCacheobject for your entire application and you definitely shouldn’t be creating one of your own.