开发者

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

开发者 https://www.devze.com 2023-03-16 01:00 出处:网络
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

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 m开发者_StackOverflow社区odel 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?


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号