System.Web.Caching.Cache throws a null exception in the model

Perhaps this question should be easy, but it is not. I read the Problem using the System.Web.Caching.Cache class in ASP.NET .

I have a singleton class:

private System.Web.Caching.Cache _cache; private static CacheModel _instance = null; private CacheModel() { _cache = new Cache(); } public static CacheModel Instance { get { return _instance ?? new CacheModel(); } } public void SetCache(string key, object value){ _cache.Insert(key, value); } 

If somewhere else in my code I call the following:

 CacheModel aCache = CacheModel.Instance; aCache.SetCache("mykey", new string[2]{"Val1", "Val2"}); //this line throws null exception 

Why does the second line throw a null reference exception?

Perhaps I allowed something in the code?

Thanks.

+4
source share
2 answers

You should not use the Cache type to initialize your own instance :

This API supports the .NET Framework and is not intended to be used directly from your code.

Ignoring why you get an exception with a null reference, and I ran into this problem before, this is related to the infrastructure and life cycle of the web application :

One instance of this class is created for each application domain and remains valid as long as the application domain remains active. Information about an instance of this class is available through the Cache property of the HttpContext object or the Cache property of the Page object.

On the bottom line, do not use the System.Web.Caching.Cache type directly in this way - either refer to the existing cache instance, or use an alternative, for example, Caching block of the corporate library application .

+9
source

As stated above, System.web.caching.cache stores ASP.NET internal data (for example, packages that were created in App_start).

Use System.Runtime.Caching . here is the walkthrough on MSDN

Here is a snippet: `

 using System.Runtime.Caching; ... ObjectCache cache = MemoryCache.Default; var test = "hello world"; cache["greeting"] = test; var greeting = (string)cache["greeting"]; 

`

In ASP.NET 4, caching is implemented using the ObjectCache class. more about MSDN

+1
source

Source: https://habr.com/ru/post/1437999/


All Articles