Question

This is more like a conceptual question. When to use Model Binding (in ASP.NET MVC Framework) and when to inject objects using IoC (lets say Autofac here) ?

One specific scenario is like lets say, I have the following action method

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

In the above scenario, is it possible to inject a user object to action method such that it automatically gets the user object using the UserId ? The resulting signature being:

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

Sorry if it all doesn't makes sense. It`s my first time using IoC.

EDIT:

This is the way to do it > http://buildstarted.com/2010/09/12/custom-model-binders-in-mvc-3-with-imodelbinder/

Was it helpful?

Solution

You can do what you need using a custom action filter. By overriding OnActionExecuting, we have access to the route data, and the action parameters of the action that will be executed. Given:

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;
  }
}

This attribute allows us to create the parameters that will be passed into the action, so we can load the user object at this point.

[BindUserProfile]
public ActionResult EditProfile(UserProfile userObj)
{

}

You'll probably need to get specific with your routes:

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

In MVC3 we get access to the new IDepedencyResolver interface, which allows us to perform IoC/SL using whatever IoC container or service locator we want, so we can push a service like a IUserProfileFactory into your filter, to then be able to create your UserProfile instance.

Hope that helps?

OTHER TIPS

Model binding is used for your data. Dependency injection is used for your business logic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top