Reputation: 14771
I am developing an ASP.NET MVC application. In my application, I need to provide REST API. So I added Web Api 2 to my existing MVC application. Before I added Web API 2, I was using ninject for dependency injection. I installed it via Nuget Package.
The whole website is already developed and working. But the problem started when I added Web Api 2 to my project. Ninject for MVC cannot be used with Web Api. So I installed Ninject for Web Api 2. So my NinjectWebCommon class has been changed after I installed it.
This is my NinjectWebCommon file in App_Start folder
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(AyarDirectory.Web.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(AyarDirectory.Web.App_Start.NinjectWebCommon), "Stop")]
namespace AyarDirectory.Web.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)
{
System.Web.Mvc.DependencyResolver.SetResolver(new AyarDirectory.Web.Infrastructure.NinjectDependencyResolver(kernel));
}
}
}
I changed only that place after I installed ninject for web api 2.Then I run my application. Website is working fine. Website is still working. But Web Api is not working.
This is my resolver class
namespace AyarDirectory.Web.Infrastructure
{
public class NinjectDependencyResolver : IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver(IKernel kernelParam)
{
kernel = kernelParam;
AddBindings();
}
public object GetService(Type serviceType)
{
return kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
private void AddBindings()
{
kernel.Bind<ICategoryRepo>().To<CategoryRepo>();
}
}
}
I do dependency injection in Api Controller like this:
public class RegionsController : ApiController
{
private IRegionRepo regionRepo;
private RegionsController(IRegionRepo regionParam)
{
this.regionRepo = regionParam;
}
. . . }
When I access one of the action of api controller, it is giving me the following error.
{"Message":"An error has occurred.","ExceptionMessage":"An error occurred when trying to create a controller of type 'RegionsController'. Make sure that the controller has a parameterless public constructor.","ExceptionType":"System.InvalidOperationException","StackTrace":" at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Type 'AyarDirectory.Web.Controllers.Api.RegionsController' does not have a default constructor","ExceptionType":"System.ArgumentException","StackTrace":" at System.Linq.Expressions.Expression.New(Type type)\r\n at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"}}
So, what is missing or wrong with my code? How can I use Ninject for Web Api 2? I am using MVC 5.
Upvotes: 0
Views: 1324
Reputation: 103
Just do 2 more steps below:
install-package Ninject.Web.WebApi
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
return kernel;
Upvotes: 1