Why is cache object stored in session when using AppFabric?
I had my first go at AppFabric - caching (aka Ms Velocity) today and checked out msdn virtual labs.
https://cmg.vlabcenter.com/default.aspx?moduleid=4d352091-dd7d-4f6c-815c-db2eafe608c7
There is this code sample in it that I dont get. It creates a cache object and stores it in session state. The documentation just says:
We need to store the cache object in Session state and retrieve the same instance of that object each time we need to use it.
Thats not the way I used to use the cache in ASP.NET. What is the reason for this pattern and do I have to use it?
private DataCache GetCache()
{
DataCache dCache;
if (Session["dCache"] != null)
{
dCache = (DataCache)Session["dCache"];
if (开发者_开发百科dCache == null)
throw new InvalidOperationException("Unable to get or create distributed cache");
}
else
{
var factory = new DataCacheFactory();
dCache = factory.GetCache("default");
Session["dCache"] = dCache;
}
return dCache;
}
This is because DataCacheFactory
is an expensive object to create - you don't want to be creating an instance of it every time you want to access the cache.
What they're showing you in the lab is how to create an instance of DataCacheFactory
once to get hold of a DataCache
instance, and then storing that DataCache instance in Session state so you can go back to that one each time you access the cache.
Of course, this still means you're creating an instance of DataCacheFactory per user, I think storing it in Application state would be an even better design.
精彩评论