2014-02-08 86 views
0

我有這樣的類實例化我的MVC控制器(我使用MVC 5,但沒有使用的WebAPI)錯誤激活的HomeController

公共類NinjectControllerFactory:DefaultControllerFactory { 私人只讀的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. 

我究竟做錯了什麼?

回答

2

你似乎很快就會處理內核(只要你創建它)。

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

當您處理內核,你基本上殺死你可能在它和運行時需要實例您HomeController的,並要求內核的時間已經註冊的一切:得到你的RegisterInjections方法擺脫using條款對於IAlbumSevrice的實例,內核已經死了,找不到這樣的實例。