在 ASP.NET MVC3 中创建依赖项感知模型绑定器

发布于 2025-01-01 21:51:43 字数 1046 浏览 1 评论 0原文

下面的代码尝试创建一个依赖感知模型绑定器。 模型绑定器应根据请求中的对象实例化一个对象。但是,我没有看到下面代码中的逻辑,它仅在对象上实例化。此外,我尝试调试它,未调用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

[浮城] 2025-01-08 21:51:43

因为我定义了一个基于属性的自定义模型绑定器,它优先于 DIModelBinder。

Because I defined an attribute-based custom model binder, which takes precedence over DIModelBinder.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文