2010-11-21 62 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

模型绑定用于数据的方式。依赖注入用于您的业务逻辑。