[英]How to override the ASP.NET MVC 3 default model binder to resolve dependencies (using ninject) during model creation?
我有一个ASP.NET MVC 3应用程序,它使用Ninject来解决依赖关系。 到目前为止,我必须做的就是使Global文件继承自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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.