How to override the ASP.NET MVC 3 default model bi

2019-04-26 16:55发布

问题:

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