Ninject: One interceptor instance per one class instance being intercepted?

陌路散爱 提交于 2019-12-24 00:16:57

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/5353476/ninject-one-interceptor-instance-per-one-class-instance-being-intercepted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!