动态代理拦截器中的通用参数



要从内存缓存中添加和检索对象,我有一个缓存util类与这些方法:

public static T GetNativeItem<T>(string itemKey)
public static void AddNativeItem(string key, object item, TimeSpan timeout)
我想使用城堡动态代理,在这种特殊情况下,我将使用Ninject.Extensions.Interception.。

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

ninectwebcommon绑定:

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);
      }
    }
  }

经过一些试探性的我在这里找到了解决方案,使用反射:

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);

相关内容

  • 没有找到相关文章

最新更新