Reputation: 343
During Application_End()
in Global.aspx, HttpContext.Current is null. I still want to be able to access cache - it's in memory, so want to see if I can reference it somehow to save bits to disk.
Question - is there a way to reference cache in memory somehow when HttpContext.Current is null?
Perhaps I could create a global static variable that would store pointer to cache that I could update on HTTP requests (pseudo: "static <pointer X>" = HttpRequest.Current
) and retrieve a reference to cache through that pointer in Application_End()?
Is there a better way to access Cache in memory when there is no Http Request is made?
Upvotes: 13
Views: 11473
Reputation: 561
I'm using the following getter to return a System.Web.Caching.Cache object which is working for me.
get
{
return (System.Web.HttpContext.Current == null)
? System.Web.HttpRuntime.Cache
: System.Web.HttpContext.Current.Cache;
}
Which basically backs up James Gaunt but of course is only going to help get the cache in Application End.
Edit: I probably got this from one of the comments on the Scott Hanselman blog James linked to!
Upvotes: 11
Reputation: 905
Inside Application_End event all cache objects are already disposed. If you want to get access to cache object before it will be disposed, you need to use somethink like this to add object to cache:
Import namespace System.Web.Caching to your application where you are using adding objects to cache.
//Add callback method to delegate
var onRemove = new CacheItemRemovedCallback(RemovedCallback);
//Insert object to cache
HttpContext.Current.Cache.Insert("YourKey", YourValue, null, DateTime.Now.AddHours(12), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, onRemove);
And when this object is going to be disposed will be called following method:
private void RemovedCallback(string key, object value, CacheItemRemovedReason reason)
{
//Use your logic here
//After this method cache object will be disposed
}
Please let me know if this approach is not right for you. Hope it will help you with your question.
Best regards, Dima.
Upvotes: 6
Reputation: 14793
You should be able to access it via HttpRuntime.Cache
http://www.hanselman.com/blog/UsingTheASPNETCacheOutsideOfASPNET.aspx
According to Scott - looking at Reflector HttpContext.Current.Cache just calls HttpRuntime.Cache - so you might as well always access it this way.
Upvotes: 30