我正在使用 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 创建一个类代理,这需要:
- 无参数构造函数
- 虚拟方法
接口(interface)代理没有此限制,但这需要 Ninject 3.0.0
关于忍者拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9383320/