我正在学习使用 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
它只有两个简单的方法,虚拟的,允许拦截器对其进行工作。 (两种方法是 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 块:
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);
}
我的原因是guessing这是有效的,因为它在幕后创建了一个代理类MyClass
并以某种方式传递IKernel
到代理。当您(在代理上)调用该方法时,它会返回内核并解决一些额外的依赖关系(包括IProxyRequestFactory
)。由于您正在处理它,因此它不再能够解决该依赖性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)