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

天大地大妈咪最大 提交于 2020-01-23 05:56:35

问题


I have an ASP.NET MVC 3 application that uses Ninject to resolve dependencies. All I've had to do so far is make the Global file inherit from NinjectHttpApplication and then override the CreateKernel method to map my dependency bindings. After that I am able to include interface dependencies in my MVC controller constructors and ninject is able to resolve them. All that is great. Now I would like to resolve dependencies in the model binder as well when it is creating an instance of my model, but I do not know how to do that.

I have a view model:

public class CustomViewModel
{
    public CustomViewModel(IMyRepository myRepository)
    {
        this.MyRepository = myRepository;
    }

    public IMyRepository MyRepository { get; set; }

    public string SomeOtherProperty { get; set; }
}

I then have an action method that accepts the view model object:

[HttpPost]
public ActionResult MyAction(CustomViewModel customViewModel)
{
    // Would like to have dependency resolved view model object here.
}

How do I override the default model binder to include ninject and resolve dependencies?


回答1:


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));


来源:https://stackoverflow.com/questions/6488529/how-to-override-the-asp-net-mvc-3-default-model-binder-to-resolve-dependencies

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