2015-07-14 1 views
0

Pour ajouter et récupérer des objets de mémoire cache, j'ai une classe util cache avec ces méthodes:l'argument générique dans intercepteur proxy dynamique

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

pour enlever un peu de bruit de la classe d'accès aux données Je voudrais utiliser Castle Dynamic Proxy, en ce cas particulier, je voudrais utiliser Ninject.Extensions.Interception.

Le problème est le GetNativeItem<T>(string itemKey) du cache util, dans mon intercepteur comment puis-je récupérer T de invocation?

Le NinjectWebCommon de liaison:

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

L'interface IMatchDataAccess ont cette signature:

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

et CacheInterceptor ont cette implémentation:

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

Répondre

0

Après quelques I found the solution here provisoire, en utilisant la réflexion :

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