How do I cache in ASP.NET?

I have some commonly used data that I would like to load from my database and cache at time Application_Start

in my global.asax file. I read the MSDN article on caching , but I'm a little confused about the correct way to do this.

The example they give for inserting data into the cache is below:

Cache.Insert("CacheItem2", "Cached Item 2");

      

So, I added the following to my global.asax file:

using System.Web.Caching;
...
Cache.Insert("audioVariables", audioVariables);

      

But it throws An object reference is required....

. Okay, great - so I created an instance of the Cache class, for example in Application_Start

:

Cache c = new Cache();
c.Insert("audioVariables", audioVariables);

      

When I call Insert

it throws an error An unhandled exception of type 'System.NullReferenceException' occurred in System.Web.dll

.

How can I insert an object into the cache on Application_Start

?

UPDATE:

Stack trace -

[NullReferenceException: Object reference not set to instance object.] System.Web.Caching.Cache.Insert (String key, Object value) +66 MyVerbalInk.MvcApplication.Application_Start () at c: \ inetpub \ VerbalInk2.0 \ MyVerbalInk \ Global.asax.cs: 26

[HttpException (0x80004005): Object reference not set to object instance.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode (HttpContext context, HttpApplication app) +9935033
System.Web.HttpApplication.RegisterEventContext handlers (MethodSub.HttpApplication.RegisterEventContext) [] +118
System.Web.HttpApplication.InitSpecial (HttpApplicationState state, MethodInfo [] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance (IntPtr + appHttpContext
. PipelineRuntime.InitializeApplication (IntPtr appContext) +296

[HttpException (0x80004005): Object reference not set to object instance.] System.Web.HttpRuntime.FirstRequestInit (HttpContext context) +9913572
System.Web.HttpRuntime.EnsureFirstRequestInit (HttpContext context) .HttpContext +101 System.Web.time ProcessRequestNotificationPrivate (IIS7WorkerRequest wr, HttpContext) +254

+3


source to share


1 answer


You probably want to read this article:

http://www.asp.net/web-forms/overview/data-access/caching-data/caching-data-at-application-startup-cs



However, the crux of the problem is that in II7 or later, running in integrated mode, there is no HttpContext in Application_Start (). You must use `HttpRuntime.Cache.Insert () 'and not Cache, or HttpContext.Current.Cache

+5


source







All Articles