How to configure an additional interception method using Ninject?

Suppose I have a class in which I sometimes want * (but now always) to intercept some (but not all) methods. As I understand it, this can be done, for example, using InterceptAround()Ninject in my module (in higher level code) or with an attribute obtained from InterceptAttribute for these methods (at the implementation level).

I do not like the first way to do this, because it requires the consumer to know the details, there will be many classes with many methods. But I also don’t like the second method, since I don’t see how to disable (or rather not enable) the interception, since the attribute is merged with the code.

Is there any known approach to solve this problem?


*: for application lifetime.

+5
source share
1 answer

It sounds like you mean a regular dynamic interceptor, which by default works on the Ninject Interception extension.

Here is an example of conditional interception:

class CustomInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        if (invocation.Request.Method.Name == "MethodToIntercept")
            Console.WriteLine("Intercepted!");
        invocation.Proceed();
    }
}

You bind it directly to one class, for example:

public class MyModule : NinjectModule
{
    public override void Load()
    {
        Bind<IFoo>().To<MyFoo>().Intercept().With<CustomInterceptor>();
    }
}

And that’s almost all you need to do if you want to dynamically intercept one class.

Kernel extensions look promising because they allow you to write conditions directly in the declaration:

kernel.Intercept(ctx => ctx.Request.Service == typeof(IFoo))
    .With<CustomInterceptor>();

, , , . , , ( ) .

run-or-don't-run , .

, (/) , , . , Ninject Interception , -. Castle , - - , . Ninject-DP2, Ninject.

Ninject Interception , , Castle DP2 . , , , .

+7

All Articles