Mad*_*han 5 c# ninject castle-dynamicproxy ninject-extensions ninject-interception
我正在学习使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
并且有一个名为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;
Run Code Online (Sandbox Code Playgroud)
我的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);
}
Run Code Online (Sandbox Code Playgroud)
我在指定的行收到以下错误.
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..
Run Code Online (Sandbox Code Playgroud)
谁能告诉我我做错了什么?
好的,我终于能够重现(忘了让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);
}
Run Code Online (Sandbox Code Playgroud)
我猜测这个工作的原因是因为它在封面下创建了一个代理类,MyClass并以某种方式传递IKernel给代理.当您调用该方法(在代理上)时,它会返回到内核并解析一些其他依赖项(包括IProxyRequestFactory).由于您正在处理它,它不再能够解决该依赖关系.
| 归档时间: |
|
| 查看次数: |
1076 次 |
| 最近记录: |