Guidance needed: injecting scoped/request services into Ocelot DelegatingHandler
My ocelot DelegatingHandler registered via builder.Services.AddOcelot() .AddDelegatingHandler<RequestHandler>(); depends on a scoped service MyService, and runtime throws, which after reading the docs would be kind of expected since DelegatingHandler are transient so can't depend on scoped services https://ocelot.readthedocs.io/en/develop/features/delegatinghandlers.html
Question
What is the recommended pattern for dependencies in Ocelot DelegatingHandler?
Specifically:
- Are constructor dependencies expected to be singleton/transient-only?
- For request-scoped data (claims, user identity, request context), should handlers resolve services inside
SendAsyncfromHttpContext.RequestServicesmaybe or from a new scope created usingIServiceScopeFactory? - Is there an official extension point preferred over
DelegatingHandlerfor scoped/request-bound logic? - Does Ocelot support creating custom DelegatingHandler instances per request (using request scope), or are handlers intentionally created from root/cached and therefore expected to avoid scoped constructor dependencies?
Why this matters
The DI error can be avoided by changing scoped dependency lifetimes, but that appears risky since Ocelot seems to cache handler/invoker instances. I’m not fully sure how that "cache" behaves internally, but it could potentially retain my dependency instance, causing stale request data or cross-request leakage.
I want to follow the intended Ocelot design for safe per-request behavior.
Environment
- Ocelot: 24.0.0
- .NET: 9
Thanks for clarifying the supported dependency/lifetime model.
Source: ThreeMammals/Ocelot