Search code examples
c#dependency-injectioncastle-windsor

How to implement dependency injection in an authentication filter attribute with castle windsor in asp.net web api?


I need to call a service to authenticate the headers passed with the request. I'm using windsor dependency injection, but it seems it is not possible to inject dependencies into attributes/filters?

I have pretty much googled the internet around but haven't found a clear working solution yet. Though this seems to be extremly important in most applications I wonder how u can fix this problem?


Solution

  • you need to do this on startup of your application

    I am using Simple Injector but doesn't matter what lib you use

    first register your filterattribute

     container.Register<JwtAuthenticationAttribute>(Lifestyle.Singleton)
    

    then in your startup.cs file you can do the following

     config.Filters.Add(container.GetInstance<JwtAuthenticationAttribute>());
    

    container in this context would be the container for your Castle Windosor initialization and registration of your services