2012-02-02 68 views
0

下面的代碼嘗試創建一個依賴感知模型綁定器。 模型聯編程序應基於請求中的對象實例化對象。但是,我沒有看到下面的代碼中的邏輯,它只在對象上實例化。此外,我嘗試調試它,不調用CreateModel方法。在ASP.NET MVC3中創建依賴感知模型綁定器

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); 
    } 
+0

究竟是什麼'代碼17-31'?你是從教科書中複製出來的嗎? – 2012-02-02 12:24:27

+0

請參閱我的糾正更新。 – Pingpong 2012-02-02 22:21:11

回答

0

因爲我定義了一個基於屬性的自定義模型綁定器,它優先於DIModelBinder。