0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372
  • Possible duplicate of [MVC5, Web API 2 and and Ninject](http://stackoverflow.com/questions/20595472/mvc5-web-api-2-and-and-ninject) – NightOwl888 May 28 '16 at 12:09
  • Yes I follwed that link. But it is not working. – Wai Yan Hein May 28 '16 at 12:18
  • Have you installed one of the hosting packages as in [this answer](http://stackoverflow.com/a/22774893/181087)? – NightOwl888 May 28 '16 at 12:37
  • No, I have not installed it. Web Api and Web application are in same project. I just put the Api controllers in another folder. So what hosting package should I install? What will be suitable for my project? – Wai Yan Hein May 28 '16 at 12:42
  • I suggest you refer to [the documentation](https://github.com/ninject/Ninject.Web.WebApi/wiki/Setting-up-an-mvc-webapi-application) for that. But do note you cannot self host an MVC application, so self host is not an option for you. – NightOwl888 May 28 '16 at 12:47
  • I installed web host.Even web application not working as well. Giving me this error. Error activating ModelValidatorProvider using binding from ModelValidatorProvider to NinjectDefaultModelValidatorProvider A cyclical dependency was detected between the constructors of two services. – Wai Yan Hein May 28 '16 at 12:49

1 Answers1

1

Just do 2 more steps below:

  1. From Nugget package manager:

install-package Ninject.Web.WebApi

  1. Now Edit NinjectWebCommon.cs File and add the following line at the end of the CreateKernel() method and before returning kernel properties:

GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);

return kernel;

Community
  • 1
  • 1
Amir
  • 105
  • 5