0

The code below tries to create a dependecy-aware model binder. The model binder should instantiate an object based on the object in the request. However, I don't see the logic in the code below, which only instantiate on object. Furthermore, I try to debug it, the CreateModel method is NOT invoked.

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

This class uses the application-wide dependency resolver to create model objects and falls back to the base class implementation if required (which uses the System.Activator class to create a model instance using the default constructor).

We have to register our binder with the application as the default model binder, which we do in the Appliction_Start method of Global.asax, as shown below.

Registering a Default Model Binder



 protected void Application_Start() {
    AreaRegistration.RegisterAllAreas();
    ModelBinders.Binders.DefaultBinder = new DIModelBinder();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    }
2
  • What the heck is Listing 17-31? Are you copying this out of a textbook? Feb 2, 2012 at 12:24
  • Please refer to my rectified update.
    – Pingpong
    Feb 2, 2012 at 22:21

1 Answer 1

0

Because I defined an attribute-based custom model binder, which takes precedence over DIModelBinder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.