Stack Trace
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at Mobile.DataStructures.Caching.Cache`2.Add(TKey key, TValue value, Func`1 autoRefresh, TimeSpan timeToExpire) in C:\Project\Caching\Cache.cs:line 68
at Mobile.DataStructures.Caching.Cache`2.Add(TKey key, TValue value, Func`1 autoRefresh) in C:\Project\Caching\Cache.cs:line 51
at Mobile.Authentication.Principal.PrincipalExtensions.AddUserPermissionsToCache(String username) in C:\Project\Helpers\Auth\PrincipalExtensions.cs:line 53
at Mobile.Authentication.Principal.PrincipalExtensions.RetrieveUserPermissions(PrincipalWithActivities principal, String username) in C:\Project\Helpers\Auth\PrincipalExtensions.cs:line 37
at Mobile.MvcApplication.Application_PostAuthenticateRequest(Object sender, EventArgs e) in C:\Project\Global.asax.cs:line 126
Cache.cs
public class Cache<TKey, TValue>
{
private static readonly IDictionary<TKey, CacheItem<TValue>> _Cache = new Dictionary<TKey, CacheItem<TValue>>();
...
/// <summary>
/// Adds the item to the cache where it will use the indicated autoRefresh function to refresh the value when expired.
/// Will set the time to expire to the indicated time.
/// </summary>
public void Add(TKey key, TValue value, Func<TValue> autoRefresh, TimeSpan timeToExpire)
{
var item = new CacheItem<TValue>()
{
Value = value,
RefreshCache = autoRefresh,
CachedOn = DateTime.Now,
TimeToExpire = timeToExpire
};
_Cache.Add(key, item); // NULL-REFERENCE EXCEPTION: This line threw the NullReferenceException.
TriggerChanged(new CacheEventArgs<TKey, TValue>(key, null, item));
// REFRESH: If the value is already null or default refresh it immediately.
if (item.Value == null || item.Value.Equals(default(TValue)))
{
var before = new CacheItem<TValue>(item);
item.Value = item.RefreshCache();
TriggerRefreshed(new CacheEventArgs<TKey, TValue>(key, before, item));
}
}
}
Enivornment & Other Details
This is part of an ASP.NET MVC 5 project and the top of the execution chain is the Application_PostAuthenticateRequest(object sender, EventArgs e)
event in the global.asax
file.
I've only experienced this immediately after deploying to the server; however, I feel like this should be able to happen at all. Shouldn't the static
variable be initialized by that point?
Question
It is static
, readonly
, and it has a static initializer. How did the line _Cache.Add(key, item);
throw a NullReferenceException
?