I am trying to set up a brand new project using MVC 5 and the latest Ninject.MVC5 nuget package. However I am getting a "No parameterless constructor defined for this object" exception.
I have searched around and found lots of answers that predate the Ninject MVC 5 nuget package that say you should create your own DependencyResolver. I have also found lots of answers about WebApi2 which I am not currently interested in.
This answer - MVC5, Web API 2 and Ninject - whilst not directly addressing my question suggests that everything should just work with the latest nuget package, and looking at the code generated in NinjectWebCommon.cs it looks like it is meant to "Just Work".
With current code I can put a breakpoint in NinjectWebCommon.cs and see it execute my configuration, so the issue appears to be that Ninject is not registering itself with MVC correctly.
So my main question is, should the latest nuget package for MVC 5 work without any further classes or code?
If not how should I get at the kernel created in NinjectWebCommon.cs for my dependency resolver class?
In case something funny has gone on, here is my App_Start\NinjectWebCommon.cs, the only line I've changed is to register MyProject.NinjectConfiguration which is a NinjectModule.
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyProject.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(MyProject.App_Start.NinjectWebCommon), "Stop")]
namespace MyProject.App_Start
{
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
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 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;
}
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Load(new MyProject.NinjectConfiguration());
}
}
}