Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 730
Chev Avatar asked Jun 27 '11 04:06

Chev


1 Answers

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));
like image 146
Darin Dimitrov Avatar answered Oct 15 '22 19:10

Darin Dimitrov