如何在模型创建期间覆盖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); } }
你可以注册任何你需要注入的视图模型:
上述就是C#学习教程:如何在模型创建期间覆盖ASP.NET MVC 3默认模型绑定器以解析依赖关系(使用ninject)?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
ModelBinders.Binders.Add(typeof(CustomViewModel), new CustomViewModelBinder(kernel));
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1269769.html