I am hoping someone can help me figure out why C#'s MemoryCache is not working the way it is supposed to.
I have a dll library containing a public static class. This static class has the functions to Add/Get strings from the Default memory cache. This is one dll. Here is the code:
using System;
using System.Runtime.Caching;
namespace ClassHelper
{
public static class CacheHelper
{
private static MemoryCache cache = MemoryCache.Default;
private static CacheEntryRemovedCallback callback = null;
private static CacheItemPolicy policy = null;
public static void Add(string key, string value)
{
callback = new CacheEntryRemovedCallback(MyCachedItemRemovedCallback);
policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTime.UtcNow.AddDays(5);
policy.RemovedCallback = callback;
cache.Set(key, value, policy);
}
public static bool Exists(string key)
{
if (cache.Contains(key))
{
return true;
}
else
{
return false;
}
}
public static object Get(string key)
{
return cache.Get(key);
}
public static void Remove(string key)
{
cache.Remove(key);
}
private static void MyCachedItemRemovedCallback(CacheEntryRemovedArguments arguments)
{
// Log these values from arguments list
String strLog = String.Concat("Reason: ", arguments.RemovedReason.ToString(), " | Key-Name: ", arguments.CacheItem.Key, " | Value-Object: ", arguments.CacheItem.Value.ToString());
}
}
}
I then have another class (non static) that calls uses the CacheHelper class to add/get items to/from the cache. This is another dll. This dll is being used at runtime twice in sequence (sequence 1 and 2). This is a BizTalk pipeline component if that helpes. When this class is exectued the first time I can see that objects are being added to the "Default" memory cache for sequence 1; however, when this class is in sequence 2 the "Default" memory cache becomes empty. The weird part is that if I run the class again I can see that the previous messages are still in the cache for sequence 1, but an empty cache shows up again for sequence 2. Looks like that static class is being instantiated twice with two different "Default" memory cache. Is this because BizTalk loads the component separately for each pipeline? If this is the case, how can I implement a common cache using MemoryCache.Default?