views:

22

answers:

0

I am modelbinding my session object. If i add the object in my action signature like so the object is bound and works correctly

public ActionResult Index(UserSession userSession)
{
    Response.Write(userSession.CompanyImagePath); // this works
// other logic etc..
    return View("Index", viewModel);
}

However i'd rather bind this on the controller constructor so i have it throughout my controller. Like so

private readonly IUserSession _userSession;

public StoreController(UserSession userSession) 
{
    _userSession = userSession;

}

This doesn't work, ie userSession is null. what is the best pattern to use here?

For reference here is my binding. This works fine.

   protected void Application_Start()
    {
        ModelBinders.Binders.Add(typeof(UserSession), new UserSessionModelBinder());
    }


public class UserSessionModelBinder : IModelBinder
{
    private const string userSessionKey = "_userSession";

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {

        if (bindingContext.Model != null)
            throw new InvalidOperationException("Cannot update instances");

        UserSession userSession = (UserSession)controllerContext.HttpContext.Session[userSessionKey];
        if (userSession == null)
        {
            userSession = new UserSession();
            userSession.CompanyImagePath = "test text";
            controllerContext.HttpContext.Session[userSessionKey] = userSession;
        }
        userSession.CompanyImagePath = "test2";
        return userSession;
    }
}