views:

29

answers:

2

I have 2 similar queries:

ICmOption optionRes = CmOptionRepository<ICmOption>
            .GetAll()
            .Where(option => option.Name == strCommandName && option.Data == strCommandOption)
            .FirstOrDefault()
            ;

IErrorType errorType = ErrorTypeRepository<IErrorType>
                    .GetAll()
                    .Where(et => et.ComponentId == (int)component.Id && et.ComponentErrorCode == strErrorCode)
                    .First()
                    ;

In both cases constant data from DB are fetched. Due to this reason I want to cache results of these queries...

the simplest solution for one request is:

    public IErrorType GetErrorType(IComponent component, string strErrorCode)
    {
        IErrorType errorType;

        string strKey = string.Concat(component.Id, "_", strErrorCode);
        lock (Dict)
        {
            if (Dict.ContainsKey(strKey))
            {
                errorType = Dict[strKey];
            }
            else
            {
                errorType = Repository
                    .GetAll()
                    .Where(et => et.ComponentId == (int)component.Id && et.ComponentErrorCode == strErrorCode)
                    .First()
                    ;
                Dict.Add(strKey, errorType);
            }
        }
        return errorType;
    }

    private static Dictionary<string, IErrorType> Dict { get { return _dict; } }

    private static readonly Dictionary<string, IErrorType> _dict
        = new Dictionary<string, IErrorType>();

I do need the similar for the 2nd entity, and few more are coming... So I want to create a class (CachableRepository) that will accept parameters, check if object for them is cached already, if not - get data from DB and put to cache. And this should work for different number of parameters..

The problem is: I don't see a simple way how to create a key for cache for a different parameters, and how to build a lambda-function for these parameters...

If you have any thought or suggestion, please share them.

Thanks a lot!

+1  A: 

My own 'quick' solution:

internal class CacheManager<TIEntity>
    where TIEntity : IEntity
{
    internal TIEntity GetObject(string strKey, Func<TIEntity> funcGetEntity)
    {
        TIEntity entity;
        lock (Dict)
        {
            if (Dict.ContainsKey(strKey))
            {
                entity = Dict[strKey];
            }
            else
            {
                entity = funcGetEntity();
                Dict.Add(strKey, entity);
            }
        }
        return entity;
    }

    private Dictionary<string, TIEntity> Dict { [DebuggerStepThrough] get { return _dict; } }

    private readonly Dictionary<string, TIEntity> _dict = new Dictionary<string, TIEntity>();
}


    public IErrorType GetErrorType(IComponent component, string strErrorCode)
    {
        string strKey = string.Concat(component.Id, "_", strErrorCode);
        IErrorType errorType = _sCacheManager.GetObject(
            strKey,
            () => Repository
                .GetAll()
                .Where(et => et.ComponentId == (int)component.Id && et.ComponentErrorCode == strErrorCode)
                .First()
            );
        return errorType;
    }

    private static CacheManager<IErrorType> _sCacheManager = new CacheManager<IErrorType>();

Please let me know if you see any better option.

Thanks a lot!

Budda
This should do but I would avoid locking while reading from dictionary. You can try reading from dictionary - if fails then acquire lock and then try reading again. Another suggestion is to use TryGet method rather than ContainsKey - currently, you are effectively making two lookups in dictionary per cache read.
VinayC
A: 

I use this method pretty much everywhere to handle caching objects in the ASP.NET cache, it could be modified to cache in a Dictionary instead.

public static T GetOrInsert<T>(string cacheKey, Func<T> creator)
{
    object cacheItem = HttpRuntime.Cache.Get(cacheKey);
    if (cacheItem is T)
    {
        return (T)cacheItem;
    }
    else
    {
        T newItem = creator();
        HttpRuntime.Cache.Insert(cacheKey, newItem);

        return newItem;
    }
}

You can then use it like

public IErrorType GetErrorType(IComponent component, string strErrorCode)
{
    string strKey = string.Concat(component.Id, "_", strErrorCode);
    return CacheUtil.GetOrInsert<IErrorType>( strKey, 
            () => Repository
                .GetAll()
                .Where(et => et.ComponentId == (int)component.Id && et.ComponentErrorCode == strErrorCode)
                .First()
    );
}
stevemegson
Couple of improvements in your solution:1) using T cacheItem = HttpRuntime.Cache.Get(cacheKey) as T - needs constraint T:Class though. 2) modifying the cacheKey within GetOrInsert method to include the type name of T within it otherwise you will have collisions if same key is used across two types.
VinayC
@VinayC I'm not sure if using `as T` really gains anything here, though you're right that I'm only using `is` to allow T to be a value type. (2) is a good point, my cache keys normally include the name of the calling method/class to avoid collisions.
stevemegson
VinayC