I am getting NullReferenceException at the _dicCache.TryGetValue(objID, out newObject);
line. And I have no Idea why this is happening at all. Can comeone point me to the right direction please?
Here is my class:
public class Cache<T>
{
public string Name { get; set; }
private Dictionary<int, T> _dicCache = new Dictionary<int, T>();
public void Insert(int objID, T obj)
{
try
{
_dicCache.Add(objID, obj);
HttpContext.Current.Cache.Insert(Name, _dicCache, null, DateTime.Now.AddMinutes(10), TimeSpan.FromMinutes(0));
}
catch (Exception)
{
throw;
}
}
public bool Get(int objID, out T obj)
{
_dicCache = (Dictionary<int, T>)HttpContext.Current.Cache.Get(Name);
try
{
return _dicCache.TryGetValue(objID, out obj);
}
catch (Exception)
{
throw;
}
}
}
And here is how I call it:
Services.Cache<Entities.User> cache = new Services.Cache<Entities.User>();
cache.Name = Enum.Cache.Names.usercache.ToString();
Entities.User user = new Entities.User();
cache.Get(pUserId, out user);
I Also have tried to change to Get class to:
public T Get(int objID, out T obj)
{
_dicCache = (Dictionary<int, T>)HttpContext.Current.Cache.Get(Name);
T newObject = (T)Activator.CreateInstance<T>();
try
{
_dicCache.TryGetValue(objID, out newObject);
obj = newObject;
return obj;
}
catch (Exception)
{
throw;
}
}
But I still get the same NullReferenceException at the _dicCache.TryGetValue(objID, out newObject);
line.
I think the only way you could have that exception is if your dictionary is null.
_dicCache.TryGetValue(objID, out newObject);
null
is a valid argument for the key (if TKey
is a reference type), though in your case it's int
.
Are you sure _dicCache
is not null
? I would check the value of the assignment:
_dicCache = (Dictionary<int, T>)HttpContext.Current.Cache.Get(Name);
The method that actually puts _dicCache into the http context's cache is the insert method which is never called in your code, hence when you try to obtain it back from the http context, you get null (you only ever call Get).
I would change the Name setter to actually put the dictionary into the http context at that time, or better yet, if you can somehow insert the dictionary into the cache in the constructor by getting the Name property as a constructor parameter. In general, I try to design classes in such a way that they are in an "uninitialized" state for the least amount of time possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With