1

我想注入依賴到我的會話字典類到我的控制器的構造函數。例如:Ninject/MVC3自定義模型活頁夾 - 錯誤激活

public AccountController(ISessionDictionary sessionDictionary) 
{ 
    this.sessionDictionary = sessionDictionary; 
} 

在我的Global.asax文件:

protected void Application_Start() 
{ 
    AreaRegistration.RegisterAllAreas(); 
    RegisterGlobalFilters(GlobalFilters.Filters); 
    RegisterRoutes(RouteTable.Routes); 

    ModelBinders.Binders.Add(typeof(ISessionDictionary), new SessionDictionaryBinder()); 
} 

我SessionDictionaryBinder:

public class SessionDictionaryBinder : IModelBinder 
{ 
    private const string sessionKey = "_seshDic"; 

    public object BindModel(ControllerContext controllerContext, 
          ModelBindingContext bindingContext) 
    { 
     if (bindingContext.Model != null) 
     { 
      throw new InvalidOperationException("Cannot update instances"); 
     } 

     ISessionDictionary seshDic = (SessionDictionary)controllerContext.HttpContext.Session[sessionKey]; 
     if (seshDic == null) 
     { 
      seshDic = new SessionDictionary(); 
      controllerContext.HttpContext.Session[sessionKey] = seshDic; 
     } 

     return seshDic; 
    } 
} 

當我去/帳號/登錄,我得到的錯誤:

Error activating ISessionDictionary 
No matching bindings are available, and the type is not self-bindable. 
Activation path: 
2) Injection of dependency ISessionDictionary into parameter sessionDictionary of constructor of  type AccountController 
1) Request for AccountController 

我正在使用Ninject進行DI,而我的其他bi包含在App_Start目錄中的文件的結果工作正常。我假設模型綁定器應該進入該文件,但語法是什麼?

乾杯!

回答

0

正如我所看到的,你正在混合一些東西。 這裏您註冊模型綁定到MVC3框架:

protected void Application_Start() 
{ 
    AreaRegistration.RegisterAllAreas(); 
    RegisterGlobalFilters(GlobalFilters.Filters); 
    RegisterRoutes(RouteTable.Routes); 

    ModelBinders.Binders.Add(typeof(ISessionDictionary), new SessionDictionaryBinder()); 
} 

Afther這個註冊你可以寫控制器動作期待一個ISessionDictionary實例,但無關與控制器構造函數。 Ninject不知道你的綁定,所以你必須在你使用的Ninject模塊中包含你的綁定(並且如果你沒有期望一個ISessionDictionary參數的動作,那麼你根本不需要模型綁定器)