2010-11-21 61 views
1

這更像是一個概念性問題。何時使用模型綁定(在ASP.NET MVC框架中)以及何時使用IoC注入對象(可以說Autofac在這裏)?依賴注入與模型綁定(ASP MVC,Autofac),何時使用?

一種具體的情況是一樣可以說,我有以下動作方法

public ActionResult EditProfile(string UserId) 
{ 
    // get user object from repository using the the UserId 
    // edit profile 
    // save changes 
    // return feedback 
} 

在上述情況下,是有可能注入一個用戶對象操作方法,使得它使用自動獲得所述用戶對象UserId?得到的簽名是:

public ActionResult EditProfile(UserProfile userObj) //userObj injected *somehow* to automatically retreive the object from repo using UserId ? 

對不起,如果一切都沒有意義。這是我第一次使用IoC。

編輯:

這是爲了做到這一點>http://buildstarted.com/2010/09/12/custom-model-binders-in-mvc-3-with-imodelbinder/

回答

1

您可以使用自定義操作過濾器來執行所需操作。通過覆蓋OnActionExecuting,我們可以訪問路線數據以及將要執行的動作的動作參數。鑑於:

public class BindUserProfileAttribute : ActionFilterAttribute 
{ 
    public override OnActionExecuting(FilterContext filterContext) 
    { 
    string id = (string)filterContext.RouteData.Values["UserId"]; 
    var model = new UserProfile { Id = id }; 

    filtextContext.ActionParameters["userObj"] = model; 
    } 
} 

此屬性允許我們創建將傳遞到動作的參數,因此我們可以在此處加載用戶對象。

[BindUserProfile] 
public ActionResult EditProfile(UserProfile userObj) 
{ 

} 

你可能需要得到具體與您的路線:

routes.MapRoute(
    "EditProfile", 
    "Account/EditProfile/{UserId}", 
    new { controller = "Account", action = "EditProfile" }); 

在MVC3我們接觸到新的IDepedencyResolver接口,它允許我們使用任何IoC容器進行的IoC/SL或我們需要服務定位器,因此我們可以將IUserProfileFactory之類的服務插入您的過濾器,然後才能創建您的UserProfile實例。

希望有幫助嗎?

+0

是的馬修,真的有道理,但我發現在下面的鏈接更好的解決方案。我們可以實現我們自己的Model Binder並從其中獲取用戶對象的回購。我發現它更符合模型綁定概念。 > http://buildstarted.com/2010/09/12/custom-model-binders-in-mvc-3-with-imodelbinder/。 – neebz 2010-11-22 03:17:08

0

模型綁定用於數據的方式。依賴注入用於您的業務邏輯。