Question

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?

Was it helpful?

Solution

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());
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top