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。
-
这就说得通了。但是,我仍然无法使其工作。通过将ModelBinderAttribute更改为不包含特定类型,Autofac似乎选择了正确的模型绑定程序,但仍无法解决模型绑定程序中的依赖性。我收到"没有为此对象定义无参数构造函数。"错误。
-
如果仍然得到"没有为此对象定义无参数构造函数"。那么Autofac绝对不会选择您的模型资料夹,否则您将收到其他错误...
-
看来RegisterWebApiModelBinders方法无法正常工作。即使您未在属性中指定类型,也需要显式注册您的模型绑定器。但是在这种情况下,您需要编写:builder.RegisterType().AsModelBin derForTypes(typeof (RequestContext));。请尝试一下,如果它能正常工作,那么我将用此信息更新我的答案。
-
做到了nemesv。非常感谢你。那么,您是说RegisterWebApiModelBinders扩展方法中存在错误吗?
-
我不知道这是否是错误。 RegisterWebApiModelBinders仍会注册您的活页夹,但不会注册AutofacWebApiModelBinderProvider所需的元数据。因为此功能在Autofac中完全没有记录,所以我不知道RegisterWebApiModelBinders方法适用于哪些用例...
-
在这种情况下,RegisterWebApiModelBinders似乎没有任何作用?通过RegisterType手动明确注册模型绑定程序时,我没有看到任何原因。
-
可能不再有必要再调用RegisterWebApiModelBinders了。。。因为它使用IModelBinder接口注册了绑定程序,但是Web API并未将其用于解析。也许这已在Web API 1.0和Web 2.0 API之间进行了更改,最终使该方法无用。但是,您可以在Autofac问题跟踪器中为此打开一个问题:code.google.com/p/autofac/issues
-
会做。再次感谢您的帮助nemesv。 code.google.com/p/autofac/issues/