带有 Ninject Ioc 容器的错误 Asp.Net Mvc 和 WebApi2 - 缺少无参数构造函数

Error Asp.Net Mvc and WebApi2 with Ninject Ioc Container - Parameterless Constructor is missing

我正在尝试在同一项目中使用 mvc 和 WebApi 设置 Asp.Net 网络应用程序,但我遇到了一些麻烦。

当我 运行 网络应用程序时,它工作得很好,我所有的 crud 测试都正常。

但是,当尝试使用我的 Web 时Api,它确实不起作用。

我正在使用 Ninject 作为我的 Ioc 容器并且我已经安装了 Ninject.Mvc5 和 Ninject.WebApi 包。

返回的错误是控制器工厂找不到无参数构造函数,所以我知道失败的是 Ninject 映射。

这是我的代码。

这是我的 mvc 控制器

public class InventarioController : Controller
{
    private readonly IInventarioAppService _inventarioAppService;

    public InventarioController(IInventarioAppService inventarioAppService)
    {
        _inventarioAppService = inventarioAppService;
    }

    // GET: Inventario
    public ActionResult Index()
    {
        var model = InventarioViewModel.ToViewModel(_inventarioAppService.All(true));
        return View(model);
    }
}

这是我的 Api 控制器

public class InventarioApiController : ApiController
{
    private readonly IInventarioAppService _inventarioAppService;

    public InventarioApiController(IInventarioAppService inventarioAppService)
    {
        _inventarioAppService = inventarioAppService;
    }

    public IHttpActionResult Get()
    {
        var model = _inventarioAppService.All(true);
        return Ok(model);
    }
}

这是我的 NinjectWebCommon

public static class NinjectWebCommon
{
    private static readonly Bootstrapper Bootstrapper = new Bootstrapper();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start() 
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        Bootstrapper.Initialize(CreateKernel);
    }

    /// <summary>
    /// Stops the application.
    /// </summary>
    public static void Stop()
    {
        Bootstrapper.ShutDown();
    }

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        var ioc = new Ioc();
        var kernel = ioc.Kernel;
        try
        {
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            RegisterServices(kernel);
            return kernel;
        }
        catch (Exception ex)
        {
            kernel.Dispose();
            throw new Exception("Erro ao criar o Kernel do Ninject", ex);
        }
    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    // ReSharper disable once UnusedParameter.Local
    private static void RegisterServices(IKernel kernel)
    {
    }        
}

这是我的 packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Antlr" version="3.4.1.9004" targetFramework="net452" />
  <package id="AutoMapper" version="4.2.0" targetFramework="net452" />
  <package id="bootstrap" version="3.0.0" targetFramework="net452" />
  <package id="Gps.Domain.Specification" version="1.0.0.0" targetFramework="net452" />
  <package id="Gps.Domain.Validation" version="1.0.0.0" targetFramework="net452" />
  <package id="jQuery" version="1.10.2" targetFramework="net452" />
  <package id="jQuery.Validation" version="1.8.0.1" targetFramework="net452" />
  <package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net452" />
  <package id="Microsoft.AspNet.Razor" version="3.2.3" targetFramework="net452" />
  <package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net452" />
  <package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net452" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net452" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net452" />
  <package id="Microsoft.AspNet.WebApi.HelpPage" version="5.2.3" targetFramework="net452" />
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net452" />
  <package id="Microsoft.AspNet.WebPages" version="3.2.3" targetFramework="net452" />
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net452" />
  <package id="Microsoft.jQuery.Unobtrusive.Validation" version="3.2.3" targetFramework="net452" />
  <package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net452" developmentDependency="true" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net452" />
  <package id="Modernizr" version="2.6.2" targetFramework="net452" />
  <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net452" />
  <package id="Ninject" version="3.2.0.0" targetFramework="net452" />
  <package id="Ninject.MVC5" version="3.2.1.0" targetFramework="net452" />
  <package id="Ninject.Web.Common" version="3.2.0.0" targetFramework="net452" />
  <package id="Ninject.Web.Common.WebHost" version="3.2.0.0" targetFramework="net452" />
  <package id="Ninject.Web.WebApi" version="3.2.4.0" targetFramework="net452" />
  <package id="Respond" version="1.2.0" targetFramework="net452" />
  <package id="WebActivatorEx" version="2.0" targetFramework="net452" />
  <package id="WebGrease" version="1.5.2" targetFramework="net452" />
</packages>

所以,我做错了什么?

更新

这是我的 Ioc class,我在 NinjecWebCommon 使用它来创建 Ninject 内核

public class Ioc
{
    public IKernel Kernel { get; set; }

    public Ioc()
    {
        Kernel = GetNinjectModules();
        ServiceLocator.SetLocatorProvider(() => new NinjectServiceLocator(Kernel));
    }

    private IKernel GetNinjectModules()
    {
        return new StandardKernel(new ServicesNinjectModule()
            , new InfraestructureNinjectModule()
            , new RepositoryNinjectModule()
            , new ApplicationNinjectModule());
    }

好的,在 Callum Linington 的帮助下,我只对我的代码做了一个简单的更改,并且它有效,就像 this link 帮助

在 WebCommon class,我设置了 Ninject.WebApi 包的依赖解析器,它解析了。

这就是我的 class 现在的样子。

public static class NinjectWebCommon
{
    private static readonly Bootstrapper Bootstrapper = new Bootstrapper();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start() 
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        Bootstrapper.Initialize(CreateKernel);
    }

    /// <summary>
    /// Stops the application.
    /// </summary>
    public static void Stop()
    {
        Bootstrapper.ShutDown();
    }

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        var ioc = new Ioc();
        var kernel = ioc.Kernel;
        try
        {
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            RegisterServices(kernel);

            // here I set the Ninject.WebApi package resolver
            GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);


            return kernel;
        }
        catch (Exception ex)
        {
            kernel.Dispose();
            throw new Exception("Erro ao criar o Kernel do Ninject", ex);
        }
    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    // ReSharper disable once UnusedParameter.Local
    private static void RegisterServices(IKernel kernel)
    {
    }        
}

您可能还会发现这个 link 很有用 - 它涉及添加包 Ninject.WebApi.DependencyResolver,然后添加

System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);

... 进入您的 CreateKernal() 方法,就在返回之前。