0

Im using web api 2

I have an authentication filter (implementing IAuthenticationFilter) that checks a token and sets a ClaimsPrinciple on both the Thread and the HttpContext. One such claim is the userId

I am using Windsor for Dependency Injection using the method described here. http://blog.ploeh.dk/2012/10/03/DependencyInjectioninASP.NETWebAPIwithCastleWindsor/

This will create the object graph for my controllers and therefore new up any dependencies that the controllers have

The problem is that one of the constructors in one of the dependency's makes a call that requires the userid

And it seems that this (the constructor call) occurs before it has been set by the authentication filter

What are my options here?

ChrisCa
  • 10,876
  • 22
  • 81
  • 118

1 Answers1

1

When Web API needs a controller, the dependency injection is used to create it. This always happens before executing the pipeline. So you cannot access to the userid which is set later.

There are at least these solutions.

  • resolve the dependency when needed (i.e. use the DI container as service locator). I don't like this one
  • lazy initialize the dependency (I don't know if Castle Windsor can do it, but it looks like it's possible: Lazy Loading using Windsor Castle) Not so bad
  • change the implementacion of that component, and receive the userid as parameter, where needed, so that it's available when you want to use it. I prefer this one
JotaBe
  • 38,030
  • 8
  • 98
  • 117