简体   繁体   English

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

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

I'm trying set-up an Asp.Net web App with mvc and WebApi in the same project but I'm in some trouble. 我正在尝试在同一项目中使用mvc和WebApi设置Asp.Net Web应用程序,但遇到了一些麻烦。

When I run web app, it works pretty fine, and all my crud tests were ok. 当我运行网络应用程序时,它运行良好,并且所有的原始测试都还可以。

But, when try use my WebApi, it really does not working. 但是,当尝试使用我的WebApi时,它确实不起作用。

I'm using Ninject as my Ioc Container and I've installed both Ninject.Mvc5 and Ninject.WebApi packages. 我使用Ninject作为我的Ioc容器,并且已经安装了Ninject.Mvc5和Ninject.WebApi软件包。

The error returned, is that the controller factory can't find a parameterless constructor, so I know that is the Ninject mapping who is failing. 返回的错误是控制器工厂找不到无参数的构造函数,所以我知道那是Ninject映射失败了。

Here is my code. 这是我的代码。

This is my mvc controller 这是我的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);
    }
}

and this is my Api Controller 这是我的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);
    }
}

here is my NinjectWebCommon 这是我的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)
    {
    }        
}

and Here is my packages.config 这是我的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>

So, what I'm doing wrong? 所以,我做错了什么?

UPDATE 更新

Here is my Ioc class, what I use at NinjecWebCommon to create the Ninject Kernel 这是我的Ioc类,我在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());
    }

Ok, after Callum Linington help, I did only a simple change in my code, and it works, just like this link help 好的,在Callum Linington帮助之后,我只对代码做了一个简单的更改,它就起作用了,就像此链接帮助一样

At the WebCommon class, I set the dependency resolver of Ninject.WebApi package, and it resolved. 在WebCommon类中,我设置了Ninject.WebApi包的依赖项解析器,并进行了解析。

This is how my class looks like now. 这是我班现在的样子。

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)
    {
    }        
}

You may also find this link useful - It involves adding the package Ninject.WebApi.DependencyResolver , then adding 您可能还会发现此链接有用-它涉及添加软件包Ninject.WebApi.DependencyResolver ,然后添加

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

... into your CreateKernal() method, just before returning. ...即将返回之前,放入您的CreateKernal()方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM