Это должно быть простым, хотя вам необходимо закодировать нужные вам детали, следуя важным деталям, вставляя мой код, поэтому некоторые переменные являются нашими обычаями, поэтому их соответствующим образом изменяйте. Вам нужно применить [ViewrCache] атрибут соответствующего метода пост создания под код и будет ли изменить метод IL соответственно во время выполнения
Создать атрибут пользовательского кэширования простиралась от PostSharp.Aspects.MethodInterceptionAspect
следующим образом:
[Serializable]
public sealed class ViewrCacheAttribute : MethodInterceptionAspect
класса Переменные:
// Cache Истечение из конфигурационного файла
private static readonly int CacheTimeOut = Convert.ToInt32(WebConfigurationManager.AppSettings[CacheSettings.CacheTimeOutKey]);
// Параметры, которые будут игнорироваться из кэша ключей
private string[] IgnoreParameters { get; set; }
Override метод OnInvoke(MethodInterceptionArgs args)
следующим образом:
// 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);
}
// Получить ключ метод Cache
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 кэшем
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;
}
// Вставка 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; }
}
Единственный способ PostSharp может добавить кэширование ваших методов ткачества IL-код при построении времени. Если вам нужно контролировать поведение кэширования во время выполнения, вы можете проверить текущую конфигурацию из кода перехвата аспект. Например, вы можете приступить к первоначальному вызову метода немедленно, если кеширование не было включено для этого конкретного метода. Конечно, это не поможет вам избежать украшения методов. – AlexD