Autofac does not resolve model dependencies

In my container, I registered my IModelBinder and Autofac model binding provider:

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

I bind my middleware to the class using the ModelBinder attribute for the class itself:

[ModelBinder(typeof(RequestContextModelBinder))]
public class RequestContext
{
    // ... properties etc.
}

And the binder model itself, with the dependency:

public class RequestContextModelBinder : IModelBinder
{
    private readonly ISomeDependency _someDependency;

    public RequestContextModelBinder(IAccountsRepository someDependency)
    {
        _someDependency = someDependency;
    }

    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        // ... _someDependency is null
    }
}

From the controller, I can verify that Autofac correctly enters both ISomeDependency and model binding. However, the dependence on the model binder is not introduced.

When accessing an endpoint that has the RequestContext class as a parameter, I get a "No parameterelss constructor" -exception constructor related to model binding.

Any ideas?


Update:

Thanks to nemesv, it turns out that, most likely, it makes no sense to call RegisterWebApiModelBindersin Web API 2. The problem was reported to Autofac.

, :

builder.RegisterType<RequestContextModelBinder>().AsModelBinderForTypes(typeof(RequestContext));
+4
1

Type ModelBinderAttribute, Wep.Api DependencyResolver.

Autofac IModelBinder, , Wep.Api , , Wep.Api Activator.CreateInctance , .

, RequestContextModelBinder self:

builder.RegisterType<RequestContextModelBinder>().AsSelf();

ModelBinderAttribute:

[ModelBinder]
public class RequestContext
{
    // ... properties etc.
}

ModelBinderAttribute , Wep.API ModelBinderProvider , AutofacWebApiModelBinderProvider, RequestContextModelBinder.

AutofacWebApiModelBinderProvider ,

builder.RegisterType<RequestContextModelBinder>()
       .AsModelBinderForTypes(typeof (RequestContext));

RegisterWebApiModelBinders , AsModelBinderForTypes .

+4

All Articles