Ninject:每个类实例被拦截一个拦截器实例?

时间:2011-03-18 14:34:45

标签: ioc-container ninject interceptor ninject-2 ninject-extensions

我目前遇到了一个问题,试图为每个被拦截的类实例连接一个拦截器实例。

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

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

我正在获取每个方法的拦截器实例。

有没有办法为每个被拦截的类型实例创建一个拦截器实例?

我在考虑命名范围,但截获的类型和拦截器不会互相引用。

2 个答案:

答案 0 :(得分:5)

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

但你可以做的不是直接在拦截器中执行拦截代码,而是获取将处理拦截的类的实例。

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

答案 1 :(得分:1)

您是否尝试过使用流畅的API来配置拦截?

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

N.B。 Intercept()扩展方法位于Ninject.Extensions.Interception.Infrastructure.Language.ExtensionsForIBindingSyntax

相关问题