HttpContext.Current.Cache vs. HttpRuntime.Cache

11,595

System.Web.Caching.Cache is the type which implements the cache for a Web application. HttpContext.Current.Cacheis just a wrapper and return HttpRuntime.Cache which is nothing but instance of System.Web.Caching.Cache.

Update

Refer to Is it OK to use HttpRuntime.Cache outside ASP.NET applications? for your second part.

Update: Why HttpRuntime.Cache needs to be wrapped?

In my Personal Opinion, HttpContext is the type which gets passed to IHttpHandler.ProcessPostBack and HttpApplication exposes HttpContext which is passed IHttpModule.Init. This would ensure all the dependencies are injected using Method injection. Hence they introduced a level of indirection.

The Handlers and Modules should be ignorant of the HttpRuntime on which they are hosted. While you are in a ASP.NET page, it is advisable to use this.Page.Cache instead HttpContext.Current.Cache or HttpRuntime.Cache as using HttpContext.Current would involve a overhead of resolving the current thread and HttpRuntime.Cache would create an external dependency. Page.Cache is initialized with the HttpContext.Cache which is passed to ProcessRequest

Share:
11,595
Elad Benda
Author by

Elad Benda

linkedin

Updated on June 15, 2022

Comments

  • Elad Benda
    Elad Benda almost 2 years

    I have been reading a bit about caching in c# 3.5. Got a bit confused and would appreciate clarification on elaborating what is the difference between

    HttpContext.Current.Cache vs HttpRuntime.Cache vs System.Web.Caching.Cache

    Also, I have read using any of the above in non-web application is not recommended but it works. What are the drawbacks?

  • Elad Benda
    Elad Benda about 12 years
    Why HttpRuntime.Cache needs to be wrapped?