This shall be simple, though you need to code the details you need, following are the important details, pasting my code, so some variables are our custom, modify them accordingly. You need to apply [ViewrCache] attribute to the relevant method post creating the underneath code and it will the modify the method IL accordingly at runtime
Create a custom caching attribute extended from PostSharp.Aspects.MethodInterceptionAspect
as follows:
[Serializable]
public sealed class ViewrCacheAttribute : MethodInterceptionAspect
Class Variables:
// Cache Expiration from Config file
private static readonly int CacheTimeOut = Convert.ToInt32(WebConfigurationManager.AppSettings[CacheSettings.CacheTimeOutKey]);
// Parameters to be ignored from the Cache Key
private string[] IgnoreParameters { get; set; }
Override the method OnInvoke(MethodInterceptionArgs args)
as follows:
// My custom implementation that you may want to change
public override void OnInvoke(MethodInterceptionArgs args)
{
// Fetch standard Cache
var cache = MemoryCache.Default;
// Fetch Cache Key using the Method arguments
string cacheKey = GetCacheKey(args); // Code pasted below
var cacheValue = cache.Get(cacheKey);
if (cacheValue != null)
{
args.ReturnValue = cacheValue;
return;
}
ReloadCache(cacheKey, args);
}
// Get Cache Key method
private string GetCacheKey(MethodInterceptionArgs args)
{
//need to exclude paging Parameters from Key
var builder = new StringBuilder();
var returnKey = new ViewrCacheKey { CallingMethodFullName = args.Method.ToString() };
// Loop through the Call arguments / parameters
foreach (var argument in args.Arguments)
{
if (argument != null)
{
if ((IgnoreParameters == null) ||
(IgnoreParameters != null && !IgnoreParameters.Contains(argument.ToString())))
builder.Append(JsonConvert.SerializeObject(argument));
}
}
returnKey.ControllerHash = builder.ToString();
return JsonConvert.SerializeObject(returnKey);
}
// Reload Cache
private Object ReloadCache(string cacheKey, MethodInterceptionArgs args)
{
//call the actual Method
base.OnInvoke(args);
//Save result into local cache
InsertCache(cacheKey, args.ReturnValue);
return args.ReturnValue;
}
// Insert Cache
private void InsertCache(string key, object value)
{
// Setting Cache Item Policy
var policy = new CacheItemPolicy
{
SlidingExpiration = new TimeSpan(0, 0, CacheTimeOut)
};
// sliding Expiration Timeout in Seconds
ObjectCache cache = MemoryCache.Default;
// Set the key,value in the cache
cache.Set(key, value, policy);
}
// ViewR Cache Key
public class ViewrCacheKey
{
/// <summary>
///
/// </summary>
public string CallingMethodFullName { get; set; }
/// <summary>
///
/// </summary>
public string ControllerHash { get; set; }
}