关于依赖项注入:Autofac无法解决模型绑定程序依赖项

Autofac not resolving model binder dependencies

在我的容器中,我已经注册了IModelBinder和Autofac模型绑定程序提供程序:

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

我使用类本身的ModelBinder属性将模型绑定程序绑定到一个类:

1
2
3
4
5
[ModelBinder(typeof(RequestContextModelBinder))]
public class RequestContext
{
    // ... properties etc.
}

以及模型绑定器本身,具有依赖性:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class RequestContextModelBinder : IModelBinder
{
    private readonly ISomeDependency _someDependency;

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

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

从控制器,我可以验证Autofac是否正确注入了ISomeDependency和模型绑定器。 但是,不会注入对模型绑定器的依赖性。

当访问具有RequestContext类作为参数的端点时,我得到了与模型绑定程序有关的" No parameterelss构造函数"异常。

有任何想法吗?

更新:

多亏了nemesv,事实证明在Web API 2中调用RegisterWebApiModelBinders没有任何意义。已经向Autofac报告了一个问题。

要注册模型联编程序,需要调用:

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


如果在ModelBinderAttribute中明确指定了Type,则Wep.Api会尝试从DependencyResolver获取具有给定类型的实例。

但是Autofac使用IModelBinder接口注册模型联编程序类型,因此当Wep.Api尝试使用其具体类型解析联编程序时,解析将失败,并且Wep.Api将回退到Activator.CreateInctance来创建模型联编程序实例,该实例在自定义上失败 构造函数。

您可以通过将RequestContextModelBinder注册为自己来解决此问题:

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

或者,您可以仅从ModelBinderAttribute中删除类型:

1
2
3
4
5
[ModelBinder]
public class RequestContext
{
    // ... properties etc.
}

如果ModelBinderAttribute中未提供任何类型,则Wep.API会向当前ModelBinderProvider询问您的模型类型的资料夹,在这种情况下,该AutofacWebApiModelBinderProvider可以正确解析您的RequestContextModelBinder

但是AutofacWebApiModelBinderProvider仅在您正确注册了活页夹后才能解析

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

因此,编写RegisterWebApiModelBinders还不够,您在注册活页夹时需要使用AsModelBinderForTypes