0

要从内存缓存中添加和检索对象,我有一个带有以下方法的缓存实用程序类:

public static T GetNativeItem<T>(string itemKey)
public static void AddNativeItem(string key, object item, TimeSpan timeout)

为了从数据访问类中删除一些噪音,我想使用Castle Dynamic Proxy,在这种特殊情况下,我会使用Ninject.Extensions.Interception

问题是GetNativeItem<T>(string itemKey)缓存实用程序的问题,在我的拦截器中如何从中T检索invocation

NinjectWebCommon 绑定:

kernel.Bind<IMatchDataAccess>().To<MatchDataAccess>().Intercept().With<CacheInterceptor>();

IMatchDataAccess 接口具有以下签名:

public interface IMatchDataAccess
{
    [Cached(minutes: 10)]
    IEnumerable<DomainModel.Match> GetMatches(MatchFilterDto matchFilter);
}

并且 CacheInterceptor 有这个实现:

public class CacheInterceptor : IInterceptor
  {
    public void Intercept(IInvocation invocation)
    {
      var cachedAttr = invocation.Request.Method.GetAttribute<CachedAttribute>();

      var p = invocation;
      if (cachedAttr == null)
      {
        invocation.Proceed();
        return;
      }

      var cacheKey = String.Concat(invocation.Request.Method.ReturnType.ToString(), ".", invocation.Request.Method.Name, "(", String.Join(", ", invocation.Request.Arguments), ")");

      /*
          problem is here
      */ 
      var p = invocation.Request.Method.ReturnType;
      var objInCache = CacheUtil.GetNativeItem<p>(cacheKey);


      if (objInCache != null)
        invocation.ReturnValue = objInCache;

      else
      {
        invocation.Proceed();
        var timeout = cachedAttr.Minutes > 0 ? new TimeSpan(0, cachedAttr.Minutes, 0) : new TimeSpan(0, 60, 0);
        CacheUtil.AddNativeItem(cacheKey, invocation.ReturnValue, timeout);
      }
    }
  }
4

1 回答 1

0

经过一番尝试,我在这里找到了解决方案,使用反射:

var method = typeof(CacheUtil).GetMethod("GetNativeItem");
      var gMethod = method.MakeGenericMethod(invocation.Request.Method.ReturnType);

      var objInCache = gMethod.Invoke(typeof(CacheUtil), BindingFlags.Static, null, new object[] { cacheKey }, CultureInfo.InvariantCulture);
于 2015-07-15T10:54:12.470 回答