2012-02-21 193 views
2

我正在开发一个带有caliburn.micro框架的WPF桌面应用程序,并且我想配置ninject拦截器,以便拦截方法调用。我想这样做是为了在集中的地方处理异常,这样我的代码周围的任何地方都没有try-catch块。Ninject拦截器

我还没有能够实现这一点,因为每次我用ninject连接所有东西,系统就会抛出一个异常。

因此,这里的一些代码:

的AppBootstrapper配置方法如下:

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

现在在我的拦截器的拦截方法:

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

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

    } 

在视图模型外观的方法像这样:

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

这就是拦截器应该如何工作。但是,这是行不通的,每次我运行该程序,并ninject试图SomeViewModel实例注入ISomeViewModel,程序执行失败,这是引发的异常(和堆栈跟踪): http://pastebin.com/qerZAjVr

希望你能帮助我,提前谢谢你。

回答

1

根据您偏好的代理库,您必须加载DynamicProxy(2)模块或LinFuModule。

另外要注意,Ninject 2.2将为SomeViewModel一类代理要求:

  1. 参数的构造函数
  2. 虚拟方法

接口代理没有这个限制,但此需要Ninject 3.0.0