如何模型创建过程中覆盖ASP.NET MVC 3默认模型绑定来解决依赖(使用ninject)? [英] How to override the ASP.NET MVC 3 default model binder to resolve dependencies (using ninject) during model creation?

查看:87
本文介绍了如何模型创建过程中覆盖ASP.NET MVC 3默认模型绑定来解决依赖(使用ninject)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC 3应用程序,使用Ninject来解决依赖关系。所有我有,到目前为止,做的是从 NinjectHttpApplication 使全局文件继承,然后重写 CreateKernel 方法地图我的依赖绑定。之后,我能够为包括我的MVC控制器的构造函数接口依赖和ninject能够解决这些问题。所有这一切是伟大的。现在我想解决,以及当它被我创造模型的实例模型绑定的依赖关系,但我不知道该怎么做。

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.

我有一个视图模型:

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.
}

我如何覆盖默认的模型绑定包括ninject和依赖关系?

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.

如果你还是坚持,<一个href=\"http://www.dominicpettifer.co.uk/Blog/39/dependency-injection-in-asp-net-mvc-2---part-2--modelbinders-viewmodels\">here's的模型绑定如何可能看起来像一个例子。这个想法是有,你重写自定义模型粘结剂 CreateModel 方法:

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

这篇关于如何模型创建过程中覆盖ASP.NET MVC 3默认模型绑定来解决依赖(使用ninject)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆