(N)inject session related class in System.Web.MVC.Controller Constructor (not Action)

StackOverflow https://stackoverflow.com/questions/19547230

  •  01-07-2022
  •  | 
  •  

before I injected my classes into every Action of a Controller. Using this ModelBinder approach:

public class AccountViewModelBinder: IModelBinder
{
    private const string sessionKey = "Account";

    private readonly IViewModelFactory _viewModelFactory;

    public AccountViewModelBinder(IViewModelFactory viewModelFactory)
    {
        _viewModelFactory = viewModelFactory;
    }

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {

        // get the Cart from the session 
        AccountViewModel account = (AccountViewModel)controllerContext.HttpContext.Session[sessionKey];

        if (account == null)
        {
            account = _viewModelFactory.CreateAccountVm();//new Cart();
            controllerContext.HttpContext.Session[sessionKey] = account;
        }

        return account;
    }
}

Controller Action:

public ActionResult Index(HomeViewModel homeVm, AccountViewModel accountVm)
{
    //do something here...
    return View();
}

But I think it is es mess to do it on every action again and again because there are allways the same for one controller.

So, how can I inject session related classes into controller constructor using ninject. I can already inject classes into conroller constructor but not session related one.

有帮助吗?

解决方案

You question is not so clear, either way:
You will also have to re-inject on every other controller with ninject.
Maybe you can have on your BaseController a method that handle binding with generics and call it when ever you need.

 protected T BindModel<T>(T model, string sessionKey){

            T account = (T)controllerContext.HttpContext.Session[sessionKey];

            if (account == null)
            {
                account = _viewModelFactory.CreateAccountVm();//new Cart();
                controllerContext.HttpContext.Session[sessionKey] = account;
            }

            return account;
    }

or, you can inject it like the following:

Bind<AccountViewModel>().ToProvider<ViewModeProvider>().InRequestScope();

class ViewModeProvider: ViewModeProvider<AccountViewModel> {
  protected override AccountViewModel CreateInstance(IContext context) {
    //put the logic from above here
    return account;
  }
}

or

Bind<AccountViewModel>().ToMethod(
    c => new AccountViewModel{/* your logic goes here*/}).InRequestScope();

or maybe I did not get you correctly

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