【问题标题】:Dependency Injection & Model Binding (ASP MVC, Autofac), When to use what?依赖注入和模型绑定(ASP MVC、Autofac),什么时候使用什么?
【发布时间】:2010-11-21 20:09:26
【问题描述】:

这更像是一个概念问题。何时使用模型绑定(在 ASP.NET MVC 框架中)以及何时使用 IoC 注入对象(这里说 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/

【问题讨论】:

    标签: asp.net-mvc-2 ioc-container autofac model-binding


    【解决方案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 实例。

    希望有帮助吗?

    【讨论】:

    • 是的 Matthew,这确实很有道理,但我在以下链接中找到了更好的解决方案。我们可以实现自己的模型绑定器并从其中的 repo 中获取用户对象。我发现它与模型绑定概念更加一致。 > buildstarted.com/2010/09/12/… .
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2013-02-09
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      • 2012-11-06
      • 2014-03-28
      • 2018-12-10
      相关资源
      最近更新 更多