C# Web API 2中的Autofac模型绑定提供程序
如何在Autofac for Web API 2中使用模型绑定扩展 在我的容器中,我尝试了以下方法:C# Web API 2中的Autofac模型绑定提供程序,c#,dependency-injection,inversion-of-control,ioc-container,autofac,C#,Dependency Injection,Inversion Of Control,Ioc Container,Autofac,如何在Autofac for Web API 2中使用模型绑定扩展 在我的容器中,我尝试了以下方法: builder.RegisterWebApiModelBinders(Assembly.GetExecutingAssembly()); builder.RegisterWebApiModelBinderProvider(); 我有以下型号活页夹: public class RequestContextModelBinder : IModelBinder { public bo
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,但文档中没有提到任何内容。您有什么想法吗?当使用Autofac解析模型绑定时,您仍然需要告诉Wep.API使用给定类型的模型绑定结构 您可以在多个级别上执行此操作:
- 您可以修饰动作方法参数:
[HttpGet, Route("{ca}/test")] public string Test([ModelBinder]RequestContext rc) { // rc is null }
- 也可以装饰模型类型本身:
[ModelBinder] public class RequestContext { // ... properties etc. }
- 或者,您可以全局配置您的类型:
GlobalConfiguration .Configuration .ParameterBindingRules .Add(typeof(RequestContext), (p) => p.BindWithModelBinding());
- 您可以修饰动作方法参数:
[HttpGet, Route("{ca}/test")] public string Test([ModelBinder]RequestContext rc) { // rc is null }
- 也可以装饰模型类型本身:
[ModelBinder] public class RequestContext { // ... properties etc. }
- 或者,您可以全局配置您的类型:
GlobalConfiguration .Configuration .ParameterBindingRules .Add(typeof(RequestContext), (p) => p.BindWithModelBinding());
ModelBinderAttribute
告诉wep.api您想在这里为您使用ModelBinder
参数。Autofac的帮助仅在于它向您自己的模型绑定中提供依赖项注入。但是动作参数匹配仍然是你的责任。哦,我明白了。除了属性之外,还有其他添加模型绑定器的方法吗?我尝试了这个,但运气不好:GlobalConfiguration.Configuration.BindParameter(typeof(RequestContext),newrequestContextModelBinder());如果RequestContext
是您自己的类型,您可以将modelbinderatAttribute
直接放在RequestContext
类上……是。但是,对于不控制类型的情况,还有其他选择吗?这里没有问题:您仍然需要使用ModelBinderAttribute
来告诉wep.api您想在这里为您使用ModelBinder
参数。Autofac的帮助仅在于它向您自己的模型绑定中提供依赖项注入。但是动作参数匹配仍然是你的责任。哦,我明白了。除了属性之外,还有其他添加模型绑定器的方法吗?我尝试了这个,但运气不好:GlobalConfiguration.Configuration.BindParameter(typeof(RequestContext),newrequestContextModelBinder());如果RequestContext
是您自己的类型,您可以将modelbinderatAttribute
直接放在RequestContext
类上……是。但是,对于您无法控制类型的情况,还有其他选择吗?谢谢。你的最后一个例子就是我想要的。谢谢。你的最后一个例子就是我要找的。