Question

I'm currently having a problem, trying to wire up exactly one interceptor instance per one instance of class being intercepted.

I'm creating and Advice in the InterceptorRegistrationStrategy and setting the callback to resolve an interceptor from the kernel (it has an injection constructor). Please note that I can only instantiate interceptor in the callback because InterceptorRegistrationStrategy does not have reference to Kernel itself.

            IAdvice advice = this.AdviceFactory.Create(methodInfo);
            advice.Callback = ((context) => context.Kernel.Get<MyInterceptor>());
            this.AdviceRegistry.Register(advice);

I'm getting an instance of interceptor per method.

Is there any way to create one interceptor instance per type instance being intercepted?

I was thinking about Named Scope, but intercepted type and interceptor do not reference each other.

Was it helpful?

Solution

That's not possible as one single interceptor is created per method for all instances of a binding.

But what you can do is not to execute the interception code directly in the interceptor but to get an instance of a class that will handle the interception.

public class LazyCountInterceptor : SimpleInterceptor
{
    private readonly IKernel kernel;

    public LazyCountInterceptor(IKernel kernel)
    {
        this.kernel = kernel;
    }

    protected override void BeforeInvoke(IInvocation invocation)
    {
        this.GetIntercpetor(invocation).BeforeInvoke(invocation);
    }

    protected override void AfterInvoke(IInvocation invocation)
    {
        this.GetIntercpetor(invocation).AfterInvoke(invocation);
    }

    private CountInterceptorImplementation GetIntercpetor(IInvocation invocation)
    {
        return this.kernel.Get<CountInterceptorImplementation>(
            new Parameter("interceptionTarget", new WeakReference(invocation.Request.Target), true));                
    }
}

public class CountInterceptorImplementation
{
    public void BeforeInvoke(IInvocation invocation)
    {
    }

    public void AfterInvoke(IInvocation invocation)
    {
    }
}

kernel.Bind<CountInterceptorImplementation>().ToSelf()
      .InScope(ctx => ((WeakReference)ctx.Parameters.Single(p => p.Name == "interceptionTarget").GetValue(ctx, null)).Target);

OTHER TIPS

Have you tried using the fluent API to configure your interception?

Bind<IInterceptor>().To<MyInterceptor>().InSingletonScope();
Bind<IService>().To<Service>().Intercept().With<IInterceptor>();

N.B. The Intercept() extension method is in Ninject.Extensions.Interception.Infrastructure.Language.ExtensionsForIBindingSyntax

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top