如何在模型创建期间覆盖ASP.NET MVC 3默认模型绑定器以解析依赖关系(使用ninject)?
我有一个ASP.NET MVC 3应用程序,它使用Ninject来解决依赖关系。 到目前为止,我所要做的就是使Global文件inheritance自NinjectHttpApplication
,然后重写CreateKernel
方法以映射我的依赖项绑定。 之后,我能够在我的MVC控制器构造函数中包含接口依赖项,并且ninject能够解析它们。 一切都很棒。 现在我想在模型绑定器中解决依赖关系,当它创建我的模型的实例时,但我不知道如何做到这一点。
我有一个视图模型:
public class CustomViewModel { public CustomViewModel(IMyRepository myRepository) { this.MyRepository = myRepository; } public IMyRepository MyRepository { get; set; } public string SomeOtherProperty { get; set; } }
然后我有一个接受视图模型对象的action方法:
[HttpPost] public ActionResult MyAction(CustomViewModel customViewModel) { // Would like to have dependency resolved view model object here. }
如何覆盖默认模型绑定器以包含ninject并解决依赖关系?
视图模型依赖于存储库是一种反模式。 不要这样做。
如果你仍然坚持, 这里有一个模型绑定器的样子的例子 。 我们的想法是使用自定义模型绑定器覆盖CreateModel
方法:
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); } }
你可以注册任何你需要注入的视图模型:
ModelBinders.Binders.Add(typeof(CustomViewModel), new CustomViewModelBinder(kernel));