激活HomeController时出错

时间:2014-02-08 22:39:33

标签: ninject asp.net-mvc-5

我有这个类用于实例化我的MVC控制器(我使用的是MVC 5但不使用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);
} }

在App_Start中我有这个类

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

在Global.asax我有

   NinjectConfig.RegisterInjections();

当我运行应用程序时,我收到此错误

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.

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您似乎很快就会处理内核(一旦创建它)。摆脱using方法中的RegisterInjections条款:

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

当你处理内核时,你基本上杀死了你可能在其中注册的所有内容,当运行时需要实例化HomeController并向内核询问IAlbumSevrice的实例时,内核已经死了而且找不到这样的例子。