拦截Ninject。 无法加载IProxyRequestFactory

我正在学习使用Ninject和Interceptor模式。

我有以下拦截器。

public class MyInterceptor:IInterceptor { public void Intercept(IInvocation invocation) { Console.WriteLine("Pre Execute: " + invocation.Request.Method.Name); foreach (var param in invocation.Request.Arguments) { Console.WriteLine("param : " + param); } invocation.Proceed(); Console.WriteLine("Post Execute: " + invocation.Request.Method.Name); Console.WriteLine("Returned: " + invocation.ReturnValue); } } 

并且有一个名为MyClass的类,它只有2个简单的方法,虚拟以允许拦截器处理它们。 (两种方法是Echo和double,这就像他们的名字所说的那样。)

我通过NuGet将Ninject,Ninject.Extensions.Interception和Ninject.Extensions.Interception.DynamicProxy添加到我的项目中。

添加了以下using语句。

 using Ninject; using Ninject.Extensions.Interception.Infrastructure.Language; using Ninject.Extensions.Interception; 

我的Main方法,它执行引导看起来像这样。

 static void Main(string[] args) { MyClass o = null; using (IKernel kernel = new StandardKernel()) { kernel.Bind().ToSelf().Intercept().With(new MyInterceptor()); o = kernel.Get(); } o.Echo("Hello World!"); // Error o.Double(5); } 

我在指定的行收到以下错误。

 Error loading Ninject component IProxyRequestFactory No such component has been registered in the kernel's component container. Suggestions: 1) If you have created a custom subclass for KernelBase, ensure that you have properly implemented the AddComponents() method. 2) Ensure that you have not removed the component from the container via a call to RemoveAll(). 3) Ensure you have not accidentally created more than one kernel.. 

谁能告诉我我做错了什么?

好的,我终于能够重现(忘了让MyClass方法虚拟化)。 我解决它的方法是从内核周围删除using块:

  static void Main(string[] args) { MyClass o = null; var kernel = new StandardKernel(); kernel.Bind().ToSelf().Intercept().With(new MyInterceptor()); o = kernel.Get(); o.Echo("Hello World!"); // Error o.Double(5); Console.ReadKey(true); } 

这个IKernel的原因是因为它在封面下为MyClass创建了一个代理类,并以某种方式将IKernel传递给代理。 当您调用该方法(在代理上)时,它会返回到内核并解析一些其他依赖项(包括IProxyRequestFactory )。 由于您正在处理它,它不再能够解决该依赖关系。