Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use AutoFac Web Api Authorization Filters through Attributes instead of injection?

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?

like image 396
Michail Michailidis Avatar asked Jun 05 '15 14:06

Michail Michailidis


1 Answers

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.

like image 195
Travis Illig Avatar answered Sep 17 '22 20:09

Travis Illig