1

I followed the instructions in this article to use Ninject for MVC 4 Web API Controller Constructor injection:

http://www.peterprovost.org/blog/2012/06/19/adding-ninject-to-web-api/

the problem that i am facing is when i call the api method i get error saying "Type 'CarController' does not have a default constructor".

i have even set break points at NinjectWebCommon.CreateKernel to see if that is being called. And that does get called when application runs.

Am i missing any thing?

by the way, i installed Ninject.Web.Common and Ninject from nuget for doing this. Here is my code:

MVC WEB API Controller:

public class CarController : ApiController
{
    private ICarService carService;

    public CarController(ICarService carService)
    {
        this.carService = carService;
    }

    [AcceptVerbs("GET")]
    public CarsResponse GetCars([FromUri] CarsRequest request)
    {         
        return this.carService.GetCars(request);
    }
}

in App_Start:

public class NinjectDependencyScope : IDependencyScope
{
    IResolutionRoot resolver;

    public NinjectDependencyScope(IResolutionRoot resolver)
    {
        this.resolver = resolver;
    }

    public object GetService(Type serviceType)
    {
        if (resolver == null)
            throw new ObjectDisposedException("this", "This scope has been disposed");

        return resolver.TryGet(serviceType);
    }

    public System.Collections.Generic.IEnumerable<object> GetServices(Type serviceType)
    {
        if (resolver == null)
            throw new ObjectDisposedException("this", "This scope has been disposed");

        return resolver.GetAll(serviceType);
    }

    public void Dispose()
    {
        IDisposable disposable = resolver as IDisposable;
        if (disposable != null)
            disposable.Dispose();

        resolver = null;
    }
}


public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
    IKernel kernel;

    public NinjectDependencyResolver(IKernel kernel)
        : base(kernel)
    {
        this.kernel = kernel;
    }

    public IDependencyScope BeginScope()
    {
        return new NinjectDependencyScope(kernel.BeginBlock());
    }
}

my NinjectWebCommon looks like this:

public static class NinjectWebCommon 
{
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    public static void Start() 
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }

    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);

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

        return kernel;
    }

    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<ICarService>().To<CarService>();
    }        
}
M. Ali Iftikhar
  • 3,125
  • 2
  • 26
  • 36
  • You'll probably find the answer in [this stackoverflow question](http://stackoverflow.com/questions/15908019/simple-injector-unable-to-inject-dependencies-in-web-api-controllers). The question is for another container, but I think the answer is general enough for you to find what you need. – Steven Jul 24 '13 at 10:51
  • What ninject packages have you installed? Please check if you have the following three installed. Ninject, Ninject.MVC3, Ninject.Web.Common in the Nuget package manager window – Amila Jul 24 '13 at 11:37
  • Also, as you are using NinjectDependencyResolver as the name for the class, please check if you have a using statement Ninject.Web.Mvc. if so, this line GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel); is not using the dependency resolver that you've defined. instead it uses what's in that assembly – Amila Jul 24 '13 at 11:42
  • i don't think i need Ninject.MVC3 for MV4 Web API. I saw few posts that said that this does not work any more. Infact the post that i referred on the top, also mentions that. – M. Ali Iftikhar Jul 24 '13 at 11:43
  • I'm using ninject as well. to solve some issues I used solutions from a pluralsight tutorial video as well as the one you've mentioned. maybe you don't have to use it. I'll give it a try by removing that Assembly from my project. – Amila Jul 24 '13 at 11:45
  • well, I just tried it and it broke my code. `No parameterless constructor defined for this object.` so it seems either we require that assembly or something else is wrong – Amila Jul 24 '13 at 11:48
  • k, let me try that ... – M. Ali Iftikhar Jul 24 '13 at 12:08
  • nope ... didnt work for me ... still says 'CarController' does not have a default constructor – M. Ali Iftikhar Jul 24 '13 at 12:17
  • will you be able to post the complete code in the NinjectWebCommon.cs file? check if you have those two lines at the top of the file `[assembly: WebActivator.PreApplicationStartMethod(typeof(Iagto.NinjectWebCommon), "Start")]` `[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(Iagto.NinjectWebCommon), "Stop")]` – Amila Jul 24 '13 at 14:13
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/34075/discussion-between-amila-and-adev) – Amila Jul 24 '13 at 14:34
  • Have you managed to make it work? – VahidNaderi Aug 02 '13 at 14:26
  • did u solve the issue? @OP – Nitin Sawant Feb 16 '15 at 05:28
  • 1
    @NitinSawant are you using WebApi or WebApi2 ... as the above discussion was for WebApi and used old manual tweaks to get ninject to work. Now with web api2 its very simple: http://aliiftikhar.azurewebsites.net/setting-up-ninject-for-web-api-2-project/ – M. Ali Iftikhar Feb 16 '15 at 10:44
  • I am using webapi MVC4 with Visual studio 2010 – Nitin Sawant Feb 16 '15 at 10:53

1 Answers1

1

I was having the same issue. I found the resolution by doing the following. I lost track of the webpage where I found the class NinjectMVCDependencyResolver.

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);
        // Install our Ninject-based IDependencyResolver into the Web API config
        GlobalConfiguration.Configuration.DependencyResolver 
            = new NinjectDependencyResolver(kernel);
        // Install into the MVC dependency resolver
        System.Web.Mvc.DependencyResolver.SetResolver(
            new NinjectMVCDependencyResolver(kernel));
        return kernel;
    }

public class NinjectMVCDependencyResolver : NinjectDependencyScope
                                            , System.Web.Mvc.IDependencyResolver
{
    private IKernel kernel;

    public NinjectMVCDependencyResolver(IKernel kernel)
        : base(kernel)
    {
        this.kernel = kernel;
    }

    public IDependencyScope BeginScope()
    {
        return new NinjectDependencyScope(kernel.BeginBlock());
    }
}
AC Thompson
  • 310
  • 1
  • 10
  • Argh...sorry, this is with a regular controller, not a web API controller. I haven't tried this with a web API controller yet. – AC Thompson Jul 27 '13 at 01:22
  • The injection is working on a web apicontroller for me as well, but it was working before I made the above changes based on the article linked in the question, so my answer is not helpful to the question. Again, my apologies. – AC Thompson Jul 27 '13 at 01:37