【发布时间】:2014-01-17 20:21:43
【问题描述】:
如何使用 Autofac for Web API 2 中的模型绑定扩展?
在我的容器中,我试过这个:
builder.RegisterWebApiModelBinders(Assembly.GetExecutingAssembly());
builder.RegisterWebApiModelBinderProvider();
我有以下模型绑定器:
public class RequestContextModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
// ...
// bindingContext.Model = RequestContext.Create(......)
}
}
我可以正确解析此模型绑定器,但我的操作方法不使用它:
[HttpGet, Route("{ca}/test")]
public string Test(RequestContext rc)
{
// rc is null
}
模型绑定器应该使用 ca 值并创建实例化 RequestContext 对象。 如果我用 ModelBinder 属性装饰 RequestContext 类,一切都会按预期工作。
我相信我需要告诉 Autofac 为 RequestContext 类使用什么 ModelBinder,但文档没有提及任何内容。你有什么想法吗?
【问题讨论】:
-
这里没有问题:你仍然需要使用
ModelBinderAttribute来告诉wep.api你想在这里使用ModelBinder作为你的参数。 Autofac 仅有助于将依赖注入到您自己的模型绑定器中。但是动作参数匹配仍然是你的责任。 -
哦,我明白了。除了属性之外,还有其他添加模型绑定器的方法吗?我试过这个没有运气: GlobalConfiguration.Configuration.BindParameter(typeof(RequestContext), new RequestContextModelBinder());
-
如果
RequestContext是您自己的类型,您可以将ModelBinderAttribute直接放在RequestContext类上... -
是的。但是,对于不控制类型的情况,还有其他选择吗?
标签: c# dependency-injection inversion-of-control ioc-container autofac