Tuesday, March 6, 2012

WebCast MSDN: Introducción a Páginas Web con ASP.NET y Razor Syntax

Hope to have you with us in this event (next 20th March). Register here.

Friday, March 2, 2012

ASP.NET Custom Method Cache

This is an experiment to caché results from static classes in an ASP.NET MVC project.

Domain services (see DDD) are static classes for this project :(.

Caché usage is as following:

image

The MethodCache.Get uses the calling method name as caché Key (in the previous code fragment TiposMoneda), so you don’t need to specify a caché key if you don’t want to.

Here is my implementation:

Code Snippet
public static class MethodCache
{
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static TResult Get<TResult>(Func<TResult> action)
        where TResult : class
    {
        string cacheKey = null;
        object cacheValue = null;
        var callingFrame = new StackTrace().GetFrames().Skip(1).FirstOrDefault();
        if (callingFrame != null)
        {
            cacheKey = callingFrame.GetMethod().DeclaringType.FullName + callingFrame.GetMethod().Name;
        }
        if (cacheKey != null)
        {
            cacheValue = System.Web.HttpContext.Current.Cache[cacheKey];
        }
        if (cacheValue == null || cacheValue.GetType() != typeof(TResult))
        {
            cacheValue = action();
            System.Web.HttpContext.Current.Cache[cacheKey] = cacheValue;
        }
        return (TResult)cacheValue;
    }
}

Note the NoInlining method option. This is a very important flag to the CLR. We don’t want to inline the method as it would interfere with the StackTrace (thus with the evaluation of the caché key).