2

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?

Jake L
  • 73
  • 1
  • 10
  • 1
    What have you already tried? What **specific** issues do you have? Please provide a [mcve]. Don't forget to read our [ask] topics, too. – dymanoid Dec 12 '18 at 15:17
  • 1
    [here](https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=98) is a useful take on DI with attributes - may help you build a solution – qujck Dec 12 '18 at 15:18

1 Answers1

2

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

Steven
  • 166,672
  • 24
  • 332
  • 435
npo
  • 1,060
  • 8
  • 9
  • 1
    NOTE: this will only work with global filters, not attribute applied filters on methods or classes. – Erik Funkenbusch Dec 12 '18 at 15:48
  • 1
    You should be very careful with this approach, as the `JwtAuthenticationAttribute`, with all its dependencies, will be kept alive forever. So only do this in case you can register the attribute as `Singleton` and you call `container.Verify()` – Steven Dec 14 '18 at 08:24