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 开发者_Go百科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
I'm not sure what is wrong with your code, because I don't know off-hand how Cache
is implemented, but a little searching uncovered the following Walkthrough from MSDN:
http://msdn.microsoft.com/en-us/library/dd997362.aspx
Caching Application Data in a WPF Application
And the following link gives an overview:
http://msdn.microsoft.com/en-us/library/dd997357.aspx
In summary, it appears that for .NET v4 onwards, caching has been moved into System.Runtime.Caching
from System.Web.Caching
.
From the look of the documentation you shouldn't be creating your own instance of the Cache
class (it says the constructor is for framework use only). Try using Cache.Get
instead?
EDIT (in response to comment)...
From the MSDN docs here:
One instance of this class is created per application domain, and it remains valid as long as the application domain remains active. Information about an instance of this class is available through the Cache property of the HttpContext object or the Cache property of the Page object.
So, it looks like Cache.Get
is available when you're within a Page; otherwise you can call HttpContext.Cache
to get the active cache. Either way, there's a single Cache
object for your entire application and you definitely shouldn't be creating one of your own.
For non ASP.NET applications use caching from System.Runtime.Caching.
Your code throws System.NullReferenceException
because internal cache CacheInternal
of System.Web.Caching.Cache
isn't initialized using internal void SetCacheInternal(CacheInternal cacheInternal)
method. It initializes by ASP.NET infrastructure in System.Web.HttpRuntime
class.
Unless I'm missing something, you're trying to use the ASP .NET cache within your WCF service. In order for this to work, you need to turn on ASP .NET compatibility using the AspNetCompatibilityRequirementsMode Enumeration. If you're self-hosting you'll have to roll your own.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class CalculatorService : ICalculatorSession
{
}
精彩评论