Friday, January 16, 2009

MemoryDictionaryCache reminder


public interface ICache
{
void Reset();
void Load();
string LoadMessage { get; set; }
}

public class MemoryDictionaryCache<T, Z> : ICache
{
public MemoryDictionaryCache(Func<Dictionary<T, Z>> loadCache, string loadMessage, Func<Dictionary<T,Z>, T, Z> retrieveValue)
{
_load = loadCache;
LoadMessage = loadMessage;
_retrieveValue = retrieveValue;
}

private Func<Dictionary<T, Z>> _load;
Func<Dictionary<T, Z>, T, Z> _retrieveValue;
public string LoadMessage { get; set; }

private Dictionary<T, Z> _cache = null;
private Dictionary<T, Z> Cache
{
get
{
if (_cache == null)
Load();
return _cache;
}
}

public void Reset()
{
_cache = null;
}

public void Load()
{
using (var waitWindow = new WaitWindow(LoadMessage ?? "Asteptati incarcarea datelor"))
{
_cache = _load();
}
}

public Z GetValue(T forKey)
{
return _retrieveValue(Cache, forKey);
}
}

private Dictionary<Type, ICache> _caches = new Dictionary<Type, ICache>();

private void Initialize()
{
_caches.Add(typeof(ContractID), new MemoryDictionaryCache<ContractID, ContractEntity>(
()=>new Dictionary<ContractID, ContractEntity>(),
"Incarc contractele",
(dic, contractID)=>dic.GetValue(contractID)));
}

public ContractEntity GetContractul(ContractID contractID)
{
return ((MemoryDictionaryCache<ContractID, ContractEntity>)_caches[typeof(ContractID)]).GetValue(contractID);
}

No comments: