0

I try to create new AuthenticationAttribute for per-request. I find a way with IAutofacAuthorizationFilter I can register in WebApiConfig, then I can use new instance for per request. However without autofac is there any way to do that.

public class AuthenticationAttribute : IAutofacAuthorizationFilter
{
    private readonly IAuthService authService;

    public AuthenticationAttribute(IAuthService authService)
    {
        this.authService = authService;
    }

    public  async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        //some actionContext control with authService
    }
}

I need to do this because IAuthService is instance per-request. I'm using Autofac for DI but I don't want to use Autofac in my code directly like this.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sonertbnc
  • 1,580
  • 16
  • 26
  • 1
    I'm sure you've [read the docs, especially on how attributes are singletons and how to work around that?](http://autofac.readthedocs.io/en/latest/integration/webapi.html#standard-web-api-filter-attributes-are-singletons) – Travis Illig Sep 05 '17 at 21:40
  • Yes, I read it. Can we say AuthorizeAttribute is still singleton but class from IAuthService created for per request – sonertbnc Sep 07 '17 at 08:25
  • 1
    You have to use service location on `RequestServices` to get a per request thing like `IAuthService` in an attribute. No DI on attributes. The docs show an example of that. – Travis Illig Sep 07 '17 at 13:13
  • You need to use a [custom IFilterProvider](https://stackoverflow.com/q/10708565/) in order to resolve your `IAuthorizationFilter` per request. No service location is necessary at all. – NightOwl888 Oct 06 '17 at 06:20

0 Answers0