0
votes

I have this class for instantiating my MVC controllers (I am using MVC 5 but not using WebApi)

public class NinjectControllerFactory : DefaultControllerFactory { private readonly IKernel _ninjectKernel;

public NinjectControllerFactory(IKernel kernel)
{
    _ninjectKernel = kernel;
}

protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
    return (controllerType == null) ? null : (IController)_ninjectKernel.Get(controllerType);
} }

In App_Start I have this class

public static class NinjectConfig
    {
        public static void RegisterInjections()
        {
            using (IKernel kernel = new StandardKernel())
            {
                ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(kernel));
                kernel.Bind<IAlbumService>().To<AlbumService>();
            }
        }
    }

In the Global.asax I have

   NinjectConfig.RegisterInjections();

When I run the application I get this error

Error activating HomeController
No matching bindings are available, and the type is not self-bindable.
Activation path:
 1) Request for HomeController

Suggestions:
 1) Ensure that you have defined a binding for HomeController.
 2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
 3) Ensure you have not accidentally created more than one kernel.
 4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
 5) If you are using automatic module loading, ensure the search path and filters are correct.

What am I doing wrong?

1

1 Answers

2
votes

You seem to be disposing of the kernel pretty quickly (as soon as you have created it). Get rid of the using clause in your RegisterInjections method:

public static void RegisterInjections()
{
    IKernel kernel = new StandardKernel();
    ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(kernel));
    kernel.Bind<IAlbumService>().To<AlbumService>();
}

When you dispose the kernel, you are basically killing everything you might have registered in it and by the time the runtime needs to instantiate your HomeController and asks the kernel for an instance of IAlbumSevrice, the kernel is already dead and cannot find such instance.