ioc-container - Ninject:每个被拦截的类实例有一个拦截器实例?

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

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

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

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

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

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

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

最佳答案

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

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

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

关于ioc-container - Ninject:每个被拦截的类实例有一个拦截器实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5353476/

相关文章:

c# - DbContext 已在自定义 RoleProvider 中处置

asp.net-mvc-4 - SignalR、WebAPI 和 MVC 共享相同的依赖解析器内核

hadoop - 在发送到 channel 之前删除空的 Flume 事件

java - Spring Boot : Interceptor to read particular field from request and set it in the response

c# - 记录 ninject 解决的依赖项应用程序启动

Angular 5's interceptor: make a second request and return its result instead of the first request' s 结果

c# - 是否可以将命名和未命名的统一注册解析为同一实例(ContainerControlled)

asp.net-mvc - 应用程序池回收后 Autofac 无法解决

c# - Unity Application Block,如何将参数传递给注入(inject)工厂?

c# - 使用 Unity 解析 Interface<T>