在 ASP.NET MVC3 中创建依赖项感知模型绑定器
下面的代码尝试创建一个依赖感知模型绑定器。 模型绑定器应根据请求中的对象实例化一个对象。但是,我没有看到下面代码中的逻辑,它仅在对象上实例化。此外,我尝试调试它,未调用 CreateModel 方法。
Creating a DI-Aware Model Binder
using System;
using System.Web.Mvc;
namespace MvcApp.Infrastructure {
public class DIModelBinder : DefaultModelBinder {
protected override object CreateModel(ControllerContext controllerContext,
ModelBindingContext bindingContext, Type modelType) {
return DependencyResolver.Current.GetService(modelType) ??
base.CreateModel(controllerContext, bindingContext, modelType);
}
}
}
此类使用应用程序范围的依赖项解析器来创建模型对象并回退到 基类实现(如果需要)(它使用 System.Activator 类创建模型 使用默认构造函数的实例)。
我们必须将我们的活页夹注册到应用程序作为默认模型活页夹,我们在 Global.asax的Appliction_Start方法,如下所示。
Registering a Default Model Binder
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
ModelBinders.Binders.DefaultBinder = new DIModelBinder();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
The code below tries to create a dependecy-aware model binder. The model binder should instantiate an object based on the object in the request. However, I don't see the logic in the code below, which only instantiate on object. Furthermore, I try to debug it, the CreateModel method is NOT invoked.
Creating a DI-Aware Model Binder
using System;
using System.Web.Mvc;
namespace MvcApp.Infrastructure {
public class DIModelBinder : DefaultModelBinder {
protected override object CreateModel(ControllerContext controllerContext,
ModelBindingContext bindingContext, Type modelType) {
return DependencyResolver.Current.GetService(modelType) ??
base.CreateModel(controllerContext, bindingContext, modelType);
}
}
}
This class uses the application-wide dependency resolver to create model objects and falls back to
the base class implementation if required (which uses the System.Activator class to create a model
instance using the default constructor).
We have to register our binder with the application as the default model binder, which we do in the
Appliction_Start method of Global.asax, as shown below.
Registering a Default Model Binder
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
ModelBinders.Binders.DefaultBinder = new DIModelBinder();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为我定义了一个基于属性的自定义模型绑定器,它优先于 DIModelBinder。
Because I defined an attribute-based custom model binder, which takes precedence over DIModelBinder.