How to override the ASP.NET MVC 3 default model binder to resolve dependencies (using ninject) during model creation?

核能气质少年 提交于 2019-12-05 05:34:04
Darin Dimitrov

Having view models depend on a repository is an anti-pattern. Don't do this.

If you still insist, here's an example of how a model binder might look like. The idea is to have a custom model binder where you override the CreateModel method:

public class CustomViewModelBinder : DefaultModelBinder
{
    private readonly IKernel _kernel;
    public CustomViewModelBinder(IKernel kernel)
    {
        _kernel = kernel;
    }

    protected override object CreateModel(ControllerContext controllerContext, 
      ModelBindingContext bindingContext, Type modelType)
    {
        return _kernel.Get(modelType);
    }
}

which you could register for any view model you need to have this injection:

ModelBinders.Binders.Add(typeof(CustomViewModel), 
  new CustomViewModelBinder(kernel));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!