我正在学习使用 Ninject 和拦截器模式。
我有以下拦截器。
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<MyClass>().ToSelf().Intercept().With(new MyInterceptor());
o = kernel.Get<MyClass>();
}
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 block :
static void Main(string[] args)
{
MyClass o = null;
var kernel = new StandardKernel();
kernel.Bind<MyClass>().ToSelf().Intercept().With(new MyInterceptor());
o = kernel.Get<MyClass>();
o.Echo("Hello World!"); // Error
o.Double(5);
Console.ReadKey(true);
}
我猜测这个方法可行的原因是因为它在幕后为MyClass
创建了一个代理类,并以某种方式传入了IKernel
到代理。当您调用该方法(在代理上)时,它会返回内核并解析一些额外的依赖项(包括 IProxyRequestFactory
)。由于您正在处理它,它不再能够解决该依赖性。
关于c# - 用 Ninject 拦截。无法加载 IProxyRequestFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12083052/