【问题标题】:Error Asp.Net Mvc and WebApi2 with Ninject Ioc Container - Parameterless Constructor is missing带有 Ninject Ioc 容器的错误 Asp.Net Mvc 和 WebApi2 - 缺少无参数构造函数
【发布时间】:2016-02-18 14:14:58
【问题描述】:

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

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

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

我使用 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 类,我在 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());
    }

【问题讨论】:

  • 你在GlobalConfiguration.DependencyResolver.Set(new NinjectDependencyResolver或类似的地方做什么
  • 是的,对不起,我之前没有发布我的 Ioc...但是我没有解析器...
  • 这就是为什么,当你创建你的 ninject 容器时,你需要将 GlobalConfiguration(又名 webapi 的配置)依赖解析器(又名它的服务定位器)设置为 ninject 容器。
  • 见here

标签: c# asp.net-mvc asp.net-web-api ninject


【解决方案1】:

好的,在 Callum Linington 的帮助下,我只对我的代码做了一个简单的更改,它就可以正常工作,就像 this linkhelp 一样

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

这就是我的班级现在的样子。

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-03-09
      • 2014-02-14
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      • 2014-01-19
      • 1970-01-01
      相关资源
      最近更新 更多