【问题标题】:Ninject/MVC3 Custom Model Binder - Error activatingNinject/MVC3 自定义模型绑定器 - 激活错误
【发布时间】:2025-12-01 19:30:01
【问题描述】:

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

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

干杯!

【问题讨论】:

    标签: asp.net-mvc-3 session custom-model-binder ninject.web.mvc


    【解决方案1】:

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

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    
        ModelBinders.Binders.Add(typeof(ISessionDictionary), new SessionDictionaryBinder());
    }
    

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

    【讨论】:

      最近更新 更多