HttpContext.Current.Cache vs. HttpRuntime.Cache

asp.net-mvc, c#, caching

Solution

`System.Web.Caching.Cache` is the type which implements the cache for a Web application. `HttpContext.Current.Cache`is 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`

Problem

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?

Original source

Related problems