I am trying to inject dependency to my session dictionary class into my controller's constructor. eg:

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

In my global.asax file:

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

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

My 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;
    }
}

When I go to /account/login, I get the error:

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

I am using Ninject for DI, and my other bindings in the file contained within the App_Start directory work fine. I am assuming the modelbinder should go into that file, but what is the syntax?

Cheers!

有帮助吗?

解决方案

As I see it you are mixing things up a little bit. Here you register your model binder to the MVC3 Framework:

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

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

Afther this registration you can write Controller actions expecting an ISessionDictionary instance, but that has nothing to do with controller constructors. Ninject doesn't know about your binding, so you have to include your binding in the Ninject module you are using (and if you don't have actions expecting an ISessionDictionary parameter, than you don't need the model binder at all)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top