c# - 用 Ninject 拦截。无法加载 IProxyRequestFactory

标签 c# ninject castle-dynamicproxy ninject-extensions ninject-interception

我正在学习使用 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/

相关文章:

c# - C# 属性可以向方法添加参数吗?

c# - 我是否总是必须等待一次性对象的异步方法而不是返回其任务?

c# - 与 Mac 配对会导致 Visual Studio 卡住

c# - 使用 Ninject 将当前用户注入(inject)我的域

asp.net-mvc - MVC、FluentValidation 和 Ninject 的单元测试接线

c# - 是否可以强制 CaSTLe DynamicProxy 生成的代理将成员实现为显式接口(interface)实现?

c# - CaSTLe DynamicProxy IInterceptor 或 ProxyGenerator 应该缓存吗?

c# - 直接添加引用和通过Nuget添加包有什么区别

c# - 从两个不同的文本框 ASP.NET C# 将两个数据插入同一列

.net - 为什么我需要 global::here?