[英]Interception with Ninject. Fails to load 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<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);
}
我猜這行得通的原因是,它在IKernel
為MyClass
創建了一個代理類,並以某種方式將IKernel
傳遞給該代理。 當您調用該方法(在代理上)時,它會返回內核並解析一些其他依賴項(包括IProxyRequestFactory
)。 由於您正在處理它,因此它不再能夠解決該依賴性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.