using System;
using System.Reflection;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using PostSharp.Aspects;
namespace Business.Shared.Attributes
{
[Serializable]
public sealed class CacheAttribute : OnMethodBoundaryAspect
{
// This field will be set by CompileTimeInitialize and serialized at build time,
// then deserialized at runtime.
private string _methodName;
// Method executed at build time.
public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo)
{
_methodName = method.DeclaringType.FullName + "." + method.Name;
}
private string GetCacheKey(object instance, Arguments arguments)
{
// If we have no argument, return just the method name so we don't uselessly allocate memory.
if (instance == null && arguments.Count == 0)
return _methodName;
// Add all arguments to the cache key. Note that generic arguments are not part of the cache
// key, so method calls that differ only by generic arguments will have conflicting cache keys.
var stringBuilder = new StringBuilder(_methodName);
stringBuilder.Append('(');
if (instance != null)
{
stringBuilder.Append(instance);
stringBuilder.Append("; ");
}
for (int i = 0; i < arguments.Count; i++)
{
stringBuilder.Append(arguments.GetArgument(i) ?? "null");
stringBuilder.Append(", ");
}
return stringBuilder.ToString();
}
// This method is executed before the execution of target methods of this aspect.
public override void OnEntry(MethodExecutionArgs args)
{
// Compute the cache key.
var cacheKey = GetCacheKey(args.Instance, args.Arguments);
// Fetch the value from the cache.
var cacheMgr = CacheFactory.GetCacheManager();
var value = cacheMgr.GetData(cacheKey);
if (value != null)
{
// The value was found in cache. Don't execute the method. Return immediately.
args.ReturnValue = value;
args.FlowBehavior = FlowBehavior.Return;
}
else
{
// The value was NOT found in cache. Continue with method execution, but store
// the cache key so that we don't have to compute it in OnSuccess.
args.MethodExecutionTag = cacheKey;
}
}
// This method is executed upon successful completion of target methods of this aspect.
public override void OnSuccess(MethodExecutionArgs args)
{
var cacheKey = (string)args.MethodExecutionTag;
var cacheMgr = CacheFactory.GetCacheManager();
cacheMgr.Add(cacheKey, args.ReturnValue);
}
}
}
Friday
Cache Attibute
Subscribe to:
Post Comments (Atom)
test smtp server with powershell
Send-MailMessage -SMTPServer smtp.domain.com -To [email protected] -From [email protected] -Subject "This is a test email" -Body ...
-
Here is instruction how to make blinking text in rainmeter: 1.right click and select " Edit skin " 2.add following code to temp...
-
Error:The element 'Schedule' has invalid child element 'RecurrenceRule'. List of possible elements expected: 'Occurring...
-
If you use Visual Studio to open a Web project that was developed for the .NET Framework 2.0, the .NET Framework 3.0, or the .NET Framework...
No comments:
Post a Comment