.net 九元';t解析构造函数依赖关系-Web API 2

.net 九元';t解析构造函数依赖关系-Web API 2,.net,ninject,asp.net-web-api2,.net,Ninject,Asp.net Web Api2,我已经移除了Unity,现在尝试使用Ninject来代替它。在大多数情况下,它是可以工作的,但是我无法让它在WebAPI2上运行良好 我有一个NinjectWebCommon.cs文件(除了添加一些注册,如果我明确解析,这些注册可以正常工作之外,我没有更改),我可以看到它正在触发一个启动事件。然而,当我试图访问web API控制器时,它抱怨没有公共的无参数构造函数 An error has occurred.","ExceptionMessage":"An error occurred when

我已经移除了Unity,现在尝试使用Ninject来代替它。在大多数情况下,它是可以工作的,但是我无法让它在WebAPI2上运行良好

我有一个NinjectWebCommon.cs文件(除了添加一些注册,如果我明确解析,这些注册可以正常工作之外,我没有更改),我可以看到它正在触发一个启动事件。然而,当我试图访问web API控制器时,它抱怨没有公共的无参数构造函数

An error has occurred.","ExceptionMessage":"An error occurred when trying to create a controller of type 'PlaceOrderController'. Make sure that the controller has a parameterless public constructor.
我已经安装了这些Nuget软件包(昨天才更新,所以应该都是最新版本):

尼尼特

Ninject.Extensions.Conventions

Ninject.Web.Common

Ninject.Web.Common.WebHost

Ninject.Web.WebApi

Ninject.Web.WebApi.WebHost

在这个阶段,我并没有做任何聪明的事情,只是一个带有构造函数的WebAPI控制器,该构造函数接受实现接口的依赖项。使用Unity,我可以在几分钟内让它工作,但Ninject似乎是一个配置噩梦

我还遗漏了哪些步骤

NinjectWebCommons.cs

public static class NinjectWebCommon 
{
    static NinjectWebCommon()
    {
        Kernel = new InterceptAllModule();
    }

    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    public static void Start()
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(() => CreateKernel(Kernel));
    }

    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        try
        {
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            RegisterServices(kernel);
            return kernel;
        }
        catch
        {
            kernel.Dispose();
            throw;
        }
    }

    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<MyInterface>().To<MyClass>().InSingletonScope();
    }
}

从错误消息中,我认为控制器“PlaceOrderController”至少应该有一个接受MyInterface作为唯一参数的公共构造函数


您可以发布控制器的代码吗?

您没有正确设置DependencyResolver。我尝试了几个Ninject包,但由于Ninject和WebAPI(以及MVC)的版本不兼容,我无法使用这些包。 本帖: 详细描述如何设置WebAPI以使用Ninject作为其依赖项解析程序

public MyController : ApiController
{
    private readonly MyInterface _myInterface;

    public MyController(MyInterface myInterface)
    {
        _myInterface = myInterface;
    }

    . . .
}