我正试图将会话字典类的依赖项注入控制器的构造函数中。例如:
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());
}
我的会话DictionaryBinder:
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,并且App_Start目录中包含的文件中的其他绑定工作正常。我假设modelbinder应该进入该文件,但语法是什么?
干杯!
在我看来,你把事情搞混了。在这里,您可以将模型绑定器注册到MVC3 Framework:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
ModelBinders.Binders.Add(typeof(ISessionDictionary), new SessionDictionaryBinder());
}
在注册之后,您可以编写期望ISessionDictionary实例的Controller操作,但这与控制器构造函数无关。Ninject不知道你的绑定,所以你必须在你正在使用的Ninject模块中包括你的绑定(如果你没有需要ISessionDictionary参数的操作,那么你根本不需要模型绑定器)