Search code examples
c#asp.net-mvcasp.net-web-apininject

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.

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.

I'm using Ninject as my Ioc Container and I've installed both Ninject.Mvc5 and Ninject.WebApi packages.

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.

Here is my code.

This is my mvc controller

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

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

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

<?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

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());
    }

Solution

  • Ok, after Callum Linington help, I did only a simple change in my code, and it works, just like this link help

    At the WebCommon class, I set the dependency resolver of Ninject.WebApi package, and it resolved.

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