Before marking this as a duplicate, please take the time to read through the question!
I have created a new web app project in VS2015, added MVC 5 and Web Api 2.
I've added the following packages to the project:
Ninject
Ninject.MVC5
Ninject.Web
Ninject.Web.Common
Ninject.Web.Common.WebHost
Ninject.Web.WebApi
Ninject.Web.WebApi.WebHost
And that created a NinjectWeb.cs
and NinjectWebCommon.cs
file in the App_Start folder. With breakpoints in both, I know they get hit on start up.
But I still get the
No parameterless constructor defined for this object
error when hitting a MVC controller and the
Make sure that the controller has a parameterless public constructor.
error when hitting a Web Api controller.
So I have a work-around that "solves" the problem, I've added these 2 lines to the CreateKernel
method of the NinjectWebCommon.cs
file:
GlobalConfiguration.Configuration.DependencyResolver = new Ninject.Web.WebApi.NinjectDependencyResolver(kernel);
System.Web.Mvc.DependencyResolver.SetResolver(new Ninject.Web.Mvc.NinjectDependencyResolver(kernel));
So the question: Where in the Ninject code should this have been handled? I would like to grap the code off GitHub to sort this out for good, but would like some hint as to where I should look?
Edit: the content of the RegisterServices
method:
private static void RegisterServices(IKernel kernel) {
// Identity
kernel.Bind<IUserStore<ApplicationUser>>()
.To<UserStore<ApplicationUser>>()
.WithConstructorArgument("connectionNameOrUrl", "User.MongoDB");
kernel.Bind<UserManager<ApplicationUser>>()
.ToSelf()
.InRequestScope()
.WithConstructorArgument("store", ctx => ctx.Kernel.Get<IUserStore<ApplicationUser>>());
// Services
// Other
kernel
.Bind<IAzureSettings>()
.To<UserAzureSettings>()
.InRequestScope();
// Providers
kernel
.Bind<WebApiUserProvider>()
.ToSelf();
kernel
.Bind<MVCUserProvider>()
.ToSelf();
kernel
.Bind<IUserProvider>()
.ToMethod((ctx) => {
if (HttpContext.Current.Handler.GetType().Namespace.StartsWith("System.Web.Mvc")) {
return ctx.Kernel.Get<MVCUserProvider>(new Ninject.Parameters.IParameter[] { });
}
else {
return ctx.Kernel.Get<WebApiUserProvider>(new Ninject.Parameters.IParameter[] { });
}
})
.InRequestScope();
}
RegisterServices()
method – Pedro Benevides