我正在尝试将我的会话字典类的依赖注入到我的控制器的构造函数中。例如:
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;
}
}
当我转到 /account/login 时,我收到错误消息:
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 目录中包含的文件中的其他绑定工作正常。我假设模型绑定器应该进入该文件,但语法是什么?
干杯!