In fact, the interception section in the Simple Injector documentation, which pretty clearly describes how to intercept. The code examples given here do not show how to work with Castle DynamicProxy, but you really need to change a few lines of code to make it work.
If you use a snippet code snippet to make it work, you only need to remove the IInterceptor and IInvocation , add using Castle.DynamicProxy to the top of the file and replace the generic Interceptor as follows:
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); } }
But at a minimum, this will be the code you need to make the interception work with Castle 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); } }; } }
Here's how to use it:
container.InterceptWith<MonitoringInterceptor>( type => type.IsInterface && type.Name.EndsWith("Repository"));
This allows you to intercept all registrations of interfaces that end in a "repository" that will be intercepted with a Transient MonitoringInterceptor .
Steven
source share