堆栈跟踪
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&amp;其他细节
这是ASP.NET MVC 5项目的一部分,执行链的顶部是Application_PostAuthenticateRequest(object sender, EventArgs e)
文件中的global.asax
事件。
我只是在部署到服务器后才立即体验到这一点;但是,我觉得这应该能够发生。那个static
变量不应该被那个点初始化吗?
问题
它是static
,readonly
,它有一个静态初始值设定项。第_Cache.Add(key, item);
行如何抛出NullReferenceException
?