dependency-injection - Autofac 未解决模型绑定(bind)器依赖项

标签 dependency-injection asp.net-web-api inversion-of-control autofac

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

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

我正在使用类本身的 ModelBinder 属性将我的模型绑定(bind)器绑定(bind)到一个类:
[ModelBinder(typeof(RequestContextModelBinder))]
public class RequestContext
{
    // ... properties etc.
}

以及模型绑定(bind)器本身,具有依赖关系:
public class RequestContextModelBinder : IModelBinder
{
    private readonly ISomeDependency _someDependency;

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

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

从 Controller 中,我可以验证 Autofac 是否正确注入(inject)了 ISomeDependency 和模型绑定(bind)器。但是,没有注入(inject)对模型绑定(bind)器的依赖。

当访问以 RequestContext 类作为参数的端点时,我得到了与模型绑定(bind)器相关的“无参数构造函数”异常。

有任何想法吗?

更新:

感谢 nemesv,事实证明调用 RegisterWebApiModelBinders 很可能没有任何意义。在 Web API 2 中。一个问题是 reported到 Autofac。

要注册模型绑定(bind)器,需要调用:
builder.RegisterType<RequestContextModelBinder>().AsModelBinderForTypes(typeof(RequestContext));

最佳答案

如果您明确指定 TypeModelBinderAttribute然后 Wep.Api 尝试从 DependencyResolver 中获取具有给定类型的实例.

但是 Autofac 使用 IModelBinder 注册模型绑定(bind)器类型。接口(interface),因此当 Wep.Api 尝试使用其具体类型解析您的活页夹时,解析失败并且 Wep.Api 将回退到 Activator.CreateInctance创建在您的自定义构造函数上失败的模型绑定(bind)器实例。

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

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

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

[ModelBinder]
public class RequestContext
{
    // ... properties etc.
}

如果 ModelBinderAttribute 中没有给出类型然后 Wep.API 询问当前 ModelBinderProvider用于您的模型类型的活页夹,在本例中为 AutofacWebApiModelBinderProvider这将解决您的RequestContextModelBinder正确。

然而 AutofacWebApiModelBinderProvider如果您已正确注册它,则仅解决您的活页夹
builder.RegisterType<RequestContextModelBinder>()
       .AsModelBinderForTypes(typeof (RequestContext));

所以写RegisterWebApiModelBinders还不够你需要使用AsModelBinderForTypes注册活页夹时。

关于dependency-injection - Autofac 未解决模型绑定(bind)器依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21201555/

相关文章:

dependency-injection - Blazor 客户端 [inject] 属性总是返回 null

Angular 将服务以编程方式注入(inject)到函数中

oop - Dependency inversion principle[DIP]中的 "Abstractions should not depend on details. Details should depend on abstractions"是什么意思?

generics - CaSTLe Windsor Ioc 解析 web.config 中的通用类

c# - 如何通过依赖注入(inject)使用 RateLimiter 的 HttpClient DelegatingHandler?

php - 访问 DI 容器

asp.net-web-api - 实现 ASP.NET WebAPI 版本控制的最佳方法是什么?

c# - OData 错误 : The query specified in the URI is not valid. 该属性不能在查询选项中使用

azure - Azure 部署的应用程序的 SendGrid 入站解析失败

c# - IOC 容器 - WCF 服务 - 我应该通过构造函数实例化所有依赖项吗?