【问题标题】:Autofac model binding provider in Web API 2Web API 2 中的 Autofac 模型绑定提供程序
【发布时间】: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


【解决方案1】:

使用 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());
    

【讨论】:

  • 谢谢。你的最后一个例子就是我要找的。​​span>
猜你喜欢
  • 2014-08-19
  • 2014-01-17
  • 1970-01-01
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多