I have an Autofac Web Api Authorization Filter like that:
public class MyAuthorizationFilter : IAutofacAuthorizationFilter
{
public void OnAuthorization(HttpActionContext actionContext){}
}
public class MyAuthorizationAttribute : Attribute
{
public MyAuthorizationAttribute() { }
}
Right now the only way I can have an Autofac Web Api Authorization Filter is through injecting it in AutofacConfig.cs:
builder.RegisterType<MyAuthorizationFilter>()
.AsWebApiAuthorizationFilterFor<MyController>(
c => c.MyMethod(default(MyModel))
).InstancePerDependency();
and it seems the attribute is ignored if I don't inject it as above
public MyController : ApiController {
[MyAuthroziationFilter] // ignored
[POST("")]
public HttpResponseMessage MyMethod(MyModel myModel) {
[...]
}
}
Is there a way to use attributes/annotations for AutoFac Web Api Authorization Filters instead of injections through AutoFac and also have their dependencies properly injected?
Unfortunately, if you want DI in your filters, you can't use attributes. 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.
If you want to use attributes, the best you can do is use service location inside standard Web API attributes. Get the request lifetime scope off the request message and manually resolve the services you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With