1

How do you use the model binding extensions in Autofac for Web API 2?

In my container, I've tried this:

builder.RegisterWebApiModelBinders(Assembly.GetExecutingAssembly());
builder.RegisterWebApiModelBinderProvider();

I have the following model binder:

public class RequestContextModelBinder : IModelBinder
{    
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        // ...
        // bindingContext.Model = RequestContext.Create(......)
    }
}

I can correctly resolve this model binder, but my action methods doesn't use it:

[HttpGet, Route("{ca}/test")]
public string Test(RequestContext rc) 
{
    // rc is null 
}

The model binder is supposed to use the ca value and create instantiate the RequestContext object. If I decorate the RequestContext class with the ModelBinder attribute, everything works as expected.

I believe that I need to tell Autofac what ModelBinder to use for the RequestContext class, but the documentation doesn't mention anything. Do you have any ideas?

Tommy Jakobsen
  • 2,323
  • 6
  • 39
  • 66
  • There is no problems here: you still need to use the `ModelBinderAttribute` to tell wep.api that you want to use a `ModelBinder` here for you parameter. Autofac only helps in that it provides dependency injection into your own model binders. But the action parameter matching is still your responsibility. – nemesv Jan 17 '14 at 20:31
  • Oh, I see. Is there another way of adding the model binder than the attribute? I tried this without luck: GlobalConfiguration.Configuration.BindParameter(typeof(RequestContext), new RequestContextModelBinder()); – Tommy Jakobsen Jan 17 '14 at 21:15
  • If the `RequestContext` is your own type you can put the `ModelBinderAttribute` directly on the `RequestContext` class... – nemesv Jan 17 '14 at 21:23
  • Yes. But is there another option, for cases when you don't control the type? – Tommy Jakobsen Jan 18 '14 at 07:53

1 Answers1

4

When using Autofac to resolve your model binders you still need to tell Wep.API to use the model binding insfrastructure for the given type.

You can do this on multiple levels:

  • You can decorate your action method paramters:

    [HttpGet, Route("{ca}/test")]
    public string Test([ModelBinder]RequestContext rc) 
    {
        // rc is null 
    }
    
  • Or you can decorate your model type itself:

    [ModelBinder]
    public class RequestContext
    {
         // ... properties etc.
    }
    
  • Or you can configure your type globally:

    GlobalConfiguration
        .Configuration
        .ParameterBindingRules
            .Add(typeof(RequestContext), (p) => p.BindWithModelBinding());
    
nemesv
  • 138,284
  • 16
  • 416
  • 359