【问题标题】:Ninject InterceptorsNinject 拦截器
【发布时间】:2012-02-21 18:48:27
【问题描述】:

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

我没能完成这个,因为每次我用 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

希望您能帮我解决这个问题,在此先感谢您。

【问题讨论】:

    标签: ninject ninject-extensions ninject-interception


    【解决方案1】:

    您必须根据您喜欢的代理库加载 DynamicProxy(2)Module 或 LinFuModule。

    另外请注意,Ninject 2.2 将为 SomeViewModel 创建一个类代理,它需要:

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

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

    【讨论】:

      猜你喜欢
      • 2012-11-04
      • 2013-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      • 2013-03-08
      相关资源
      最近更新 更多