1

我正在尝试将我的会话字典类的依赖注入到我的控制器的构造函数中。例如:

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 目录中包含的文件中的其他绑定工作正常。我假设模型绑定器应该进入该文件,但语法是什么?

干杯!

4

1 回答 1

0

正如我所看到的,你把事情搞混了一点。在这里,您将模型绑定器注册到 MVC3 框架:

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

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

在此注册之后,您可以编写期望 ISessionDictionary 实例的控制器操作,但这与控制器构造函数无关。Ninject 不知道您的绑定,因此您必须将您的绑定包含在您正在使用的 Ninject 模块中(如果您没有需要 ISessionDictionary 参数的操作,那么您根本不需要模型绑定器)

于 2012-03-27T10:14:56.613 回答