gpt4 book ai didi

asp.net-web-api - 有没有办法通过属性而不是注入(inject)来使用 AutoFac Web Api 授权过滤器?

转载 作者:行者123 更新时间:2023-12-02 17:29:07 25 4
gpt4 key购买 nike

我有一个像这样的 Autofac Web Api 授权过滤器:

public class MyAuthorizationFilter : IAutofacAuthorizationFilter
{
public void OnAuthorization(HttpActionContext actionContext){}
}

public class MyAuthorizationAttribute : Attribute
{
public MyAuthorizationAttribute() { }
}

现在,我拥有 Autofac Web Api 授权过滤器的唯一方法是将其注入(inject) AutofacConfig.cs 中:

builder.RegisterType<MyAuthorizationFilter>()
.AsWebApiAuthorizationFilterFor<MyController>(
c => c.MyMethod(default(MyModel))
).InstancePerDependency();

如果我不按照上面的方式注入(inject)该属性,它似乎会被忽略

public MyController : ApiController {

[MyAuthroziationFilter] // ignored
[POST("")]
public HttpResponseMessage MyMethod(MyModel myModel) {
[...]
}
}

有没有办法使用 AutoFac Web Api 授权过滤器的属性/注释而不是通过 AutoFac 进行注入(inject),并正确注入(inject)它们的依赖项?

最佳答案

不幸的是,如果您希望在过滤器中使用 DI,则无法使用属性。 Per the docs :

Unlike the filter provider in MVC, the one in Web API does not allow you to specify that the filter instances should not be cached. This means that all filter attributes in Web API are effectively singleton instances that exist for the entire lifetime of the application.

如果您想使用属性,最好的办法是在标准 Web API 属性中使用服务位置。从请求消息中获取请求生命周期范围并手动解析您需要的服务。

关于asp.net-web-api - 有没有办法通过属性而不是注入(inject)来使用 AutoFac Web Api 授权过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30669509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com