忍者拦截器

标签 ninject ninject-extensions ninject-interception

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

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

    }

View 模型中的方法如下所示:

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

这就是拦截器应该如何工作的。但它不起作用,每次我运行程序,ninject 尝试将 SomeViewModel 的实例注入(inject) ISomeViewModel 时,程序执行失败,这是抛出的异常(以及堆栈跟踪): http://pastebin.com/qerZAjVr

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

最佳答案

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

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

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

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

关于忍者拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9383320/

相关文章:

c# - Ninject Factory 扩展与 Lazy<T>

asp.net-mvc - Ninject,如何通过调用 LoggerFactory.CreateLogger 注入(inject)通用 Logger<T>

Ninject 拦截具有特定属性的任何方法?

.net - AutoMapper 配置文件和单元测试

asp.net-mvc - 将 Ninject 更改为 Asp MVC 的 Autofac 等效项

c# - Ninject 方法级拦截带参数

ninject - weakeventmessagebroker 和 messagebroker Ninject 扩展是否已弃用?

asp.net-mvc - 如何使用 Ninject 拦截来拦截所有 ASP.NET WebApi Controller 操作方法调用以进行日志记录?

c# - 在接口(interface)上拦截

c# - 我应该如何在事务中包装我的选择语句?