2014-07-01 12 views

risposta

11

C'è in effetti una section about Interception nel iniettore semplice documentation che descrive abbastanza chiaramente come fare intercettazioni. Gli esempi di codice forniti non mostrano come lavorare con Castle DynamicProxy, ma è necessario modificare alcune righe di codice per farlo funzionare.

Se si utilizza il Interception Extensions code snippet, per farlo funzionare, è sufficiente rimuovere le IInterceptor e IInvocation interfacce, aggiungere un using Castle.DynamicProxy sulla parte superiore del file, e sostituire il generico Interceptor con il seguente:

public static class Interceptor 
{ 
    private static readonly ProxyGenerator generator = new ProxyGenerator(); 

    public static object CreateProxy(Type type, IInterceptor interceptor, 
     object target) 
    { 
     return generator.CreateInterfaceProxyWithTarget(type, target, interceptor); 
    } 
} 

Ma come minimo, questo sarebbe il codice è necessario per ottenere l'intercettazione di lavoro con il Castello DynamicProxy:

using System; 
using System.Linq.Expressions; 
using Castle.DynamicProxy; 
using SimpleInjector; 

public static class InterceptorExtensions 
{ 
    private static readonly ProxyGenerator generator = new ProxyGenerator(); 

    private static readonly Func<Type, object, IInterceptor, object> createProxy = 
     (p, t, i) => generator.CreateInterfaceProxyWithTarget(p, t, i); 

    public static void InterceptWith<TInterceptor>(this Container c, 
     Predicate<Type> predicate) 
     where TInterceptor : class, IInterceptor 
    { 
     c.ExpressionBuilt += (s, e) => 
     { 
      if (predicate(e.RegisteredServiceType)) 
      { 
       var interceptorExpression = 
        c.GetRegistration(typeof(TInterceptor), true).BuildExpression(); 

       e.Expression = Expression.Convert(
        Expression.Invoke(Expression.Constant(createProxy), 
         Expression.Constant(e.RegisteredServiceType, typeof(Type)), 
         e.Expression, 
         interceptorExpression), 
        e.RegisteredServiceType); 
      } 
     }; 
    } 
} 

questo è come utilizzare questo:

container.InterceptWith<MonitoringInterceptor>(
    type => type.IsInterface && type.Name.EndsWith("Repository")); 

Questo permette intercettare tutte le registrazioni di interfaccia il cui nome end con 'Repository' essere intercettati con un transitorio MonitoringInterceptor.

+0

davvero bello, ma ho bisogno di trovare il modo di testare. molti metodi statici e nessuna presa in giro. –

Problemi correlati