I am having a Web API application in which the controller has Services/Repositories etc. injected into it through Dependency Injection (Unity). Let's assume that I have an IStuffService
that needs the IPrincipal
of the current request (or a wrapper around it).
The problem with Web API seems to be that the only reliable source of the current Request/User is the Request
property on the instance of the ApiController
. Anything static (be it HttpContext.Current
, CallContext.Get/SetData
or Thread.Get/SetData
) is not guaranteed to be on the same thread due to the sync nature of Web API.
How do I reliably ensure that Request-specific context is passed through dependencies, and more importantly, that the operation retains the correct IPrincipal
all the way through the operation?
Two options:
- Every method that needs an
IPrincipal
has it as an argument to the method - that is the most reliable way, but it also requires me to have that thing in every method signature - Inject the IPrincipal into the ctor of the Service, spinning up a new insance of the object graph on every request, using a DependencyOverride in Unity:
container.Resolve(opType, new DependencyOverride(typeof(IPrincipal), principal))
Option 2 means that my method signatures are clean, but it also means I need to make sure all dependencies are using the TransientLifetimeManager, not a Singleton or even Per-Thread one.
Is there a better solution than I'm not seeing?