Ninject:每拦截一个类实例一个拦截器实例? [英] Ninject: One interceptor instance per one class instance being intercepted?

查看:137
本文介绍了Ninject:每拦截一个类实例一个拦截器实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前遇到问题,试图为每个要拦截的类实例准确地连接一个拦截器实例.

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

我正在InterceptorRegistrationStrategy中创建和建议,并设置回调以从内核解析拦截器(它具有注入构造函数).请注意,我只能在回调中实例化拦截器,因为InterceptorRegistrationStrategy没有引用内核本身.

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.

推荐答案

这是不可能的,因为为绑定的所有实例的每个方法都创建了一个拦截器.

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

这篇关于Ninject:每拦截一个类实例一个拦截器实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆