Created
November 20, 2015 15:51
-
-
Save asimmon/90f67c1a42a0a5dcd2a5 to your computer and use it in GitHub Desktop.
Caching method results with AOP - CacheResultInterceptor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CacheResultInterceptor : IInterceptor | |
{ | |
private readonly ICacheProvider _cache; | |
public CacheResultInterceptor(ICacheProvider cache) | |
{ | |
_cache = cache; | |
} | |
public CacheResultAttribute GetCacheResultAttribute(IInvocation invocation) | |
{ | |
return Attribute.GetCustomAttribute( | |
invocation.MethodInvocationTarget, | |
typeof(CacheResultAttribute) | |
) | |
as CacheResultAttribute; | |
} | |
public string GetInvocationSignature(IInvocation invocation) | |
{ | |
return String.Format("{0}-{1}-{2}", | |
invocation.TargetType.FullName, | |
invocation.Method.Name, | |
String.Join("-", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray()) | |
); | |
} | |
public void Intercept(IInvocation invocation) | |
{ | |
var cacheAttr = GetCacheResultAttribute(invocation); | |
if (cacheAttr == null) | |
{ | |
invocation.Proceed(); | |
return; | |
} | |
string key = GetInvocationSignature(invocation); | |
if (_cache.Contains(key)) | |
{ | |
invocation.ReturnValue = _cache.Get(key); | |
return; | |
} | |
invocation.Proceed(); | |
var result = invocation.ReturnValue; | |
if (result != null) | |
{ | |
_cache.Put(key, result, cacheAttr.Duration); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment