Daniel
Daniel

Reputation: 2534

Ninject Interceptors

I'm developing a WPF desktop application with caliburn.micro framework, and I want to configure ninject interceptors so that I can intercept method calls. I would like to do this to handle exceptions in a centralized place, so that I don't have many try-catch blocks everywhere around my code.

I haven't been able to acomplish this, because everytime I wire everything up with ninject, the system throws an exception.

So here's some code:

The AppBootstrapper configure method looks like this:

    protected override void Configure()
    {
        _kernel = new StandardKernel(new NinjectServiceModule());
        _kernel.Bind<IWindowManager>().To<WindowManager>().InSingletonScope();
        _kernel.Bind<IEventAggregator>().To<EventAggregator>().InSingletonScope();
        _kernel.Bind<ISomeViewModel>().To<SomeViewModel>().Intercept().With<SomeInterceptor>() //this is where the exception is thrown;
        _kernel.Bind<IShell>().To<ShellViewModel>();
    }

Now the intercept method in my interceptor:

    public void Intercept(IInvocation invocation)
    {
        if (invocation.Request.Method.Name == "TheMethodIWantIntercepted")
        {
            try
            {
                invocation.Proceed();
            }
            catch (Exception)
            {

                Console.WriteLine("I Handled exception");
            }
        }
        else
        {
            invocation.Proceed();
        }

    }

The method in the view model looks like this:

    public virtual void TheMethodIWantIntercepted()
    {
        //Some logic here
    }

So that's how interceptors are supposed to work. But it doesn't work, everytime I run the program, and ninject tries to inject the instance of SomeViewModel into ISomeViewModel, the program execution fails, and this is the exception that is thrown (and the stack trace): http://pastebin.com/qerZAjVr

Hope you can help me with this, thank you in advance.

Upvotes: 2

Views: 1509

Answers (1)

Remo Gloor
Remo Gloor

Reputation: 32725

You have to load either DynamicProxy(2)Module or LinFuModule depending on what proxy library you prefer.

Also be aware that Ninject 2.2 will create a class proxy for SomeViewModel which requires:

  1. a parameterless constructor
  2. virtual methods

Interface proxies don't have this restriction but this requires Ninject 3.0.0

Upvotes: 2

Related Questions